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?
- The
ifcheck only runs once: When you callcontaTempo(), theif (this.state.tempo >=5)runs immediately—before any of thesetIntervalcallbacks have had a chance to increment thetempostate. Sincetempostarts at a value less than 5 (I assume), this check never triggers again after the initial function call. - 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 incrementingtempo—sincesetStateis asynchronous, relying onthis.state.tempodirectly can lead to stale values. - Condition inside the interval callback: Now we check if
novoTempomeets 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
相关产品推荐
相关产品推荐

