You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中setInterval无法停止且判断逻辑失效求助

Hey there! Let's break down what's going wrong with your code and fix it step by step.

What's causing the issues?

  1. The if check only runs once: When you call contaTempo(), the if (this.state.tempo >=5) runs immediately—before any of the setInterval callbacks have had a chance to increment the tempo state. Since tempo starts at a value less than 5 (I assume), this check never triggers again after the initial function call.
  2. No way to stop the interval: You're not storing the ID returned by setInterval, so there's no way to clear it later. That's why your timer runs forever.

Here's the fixed code

First, we'll store the interval ID on your component instance so we can clear it when needed. Then, we'll move the condition check inside the setInterval callback (and use functional state updates to avoid stale state issues):

class SeuComponente extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tempo: 0
    };
    this.intervalId = null; // Store interval ID here
  }

  contaTempo = () => {
    // Clear any existing interval first to prevent duplicates
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }

    this.intervalId = setInterval(() => {
      this.setState(prevState => {
        const novoTempo = prevState.tempo + 1;
        
        // Check condition AFTER calculating new tempo
        if (novoTempo >= 5) {
          clearInterval(this.intervalId); // Stop the timer
          this.props.navigation.navigate('Sobre'); // Navigate
        }

        return { tempo: novoTempo };
      });
    }, 1000);
  };

  componentWillUnmount() {
    // Clean up interval when component unmounts to prevent memory leaks
    if (this.intervalId) {
      clearInterval(this.intervalId);
    }
  }

  // Rest of your component code...
}

Key fixes explained:

  • Functional state update: Using this.setState(prevState => ...) ensures we always use the latest state value when incrementing tempo—since setState is asynchronous, relying on this.state.tempo directly can lead to stale values.
  • Condition inside the interval callback: Now we check if novoTempo meets the threshold every time the timer ticks, right after calculating the new value.
  • Store interval ID: This lets us clear the timer both when we trigger the navigation and when the component unmounts (to avoid memory leaks).
  • Clear existing intervals: Before starting a new interval, we clear any existing one—this prevents multiple timers from running if contaTempo() is called more than once.

内容的提问来源于stack exchange,提问作者Italo Rodrigo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:00:09