clearInterval 不会在 useEffect 中停止我的计数器 [英] clearInterval not stopping my counter in useEffect
问题描述
我正在尝试在 useEffect
React 钩子中使用 setInterval
和 clearInterval
.计时器按预期启动,但不会停止.我将 setInterval
分配给 intervalID
然后调用 clearInterval(intervalID)
I'm trying to use a setInterval
and a clearInterval
within useEffect
React hook. The timer starts as expected, but it won't stop.
I am assigning setInterval
to intervalID
then calling clearInterval(intervalID)
useEffect(() => {
console.log(`isRunning changed to: ${state.isRunning}`); //isRunning changed to: start
let intervalID;
console.log(`initial interval is: ${intervalID}`); // initial interval is: undefined
if (state.isRunning === "start") {
intervalID = setInterval(() => {
console.log(`interval is: ${intervalID}`); // interval is: 7
console.log(`tic toc`);
dispatch({ type: "tic-toc" });
}, 1000);
} else if (state.isRunning === "stop") {
console.log("clearInterval stop!"); // when I set isRunning to stop, this log shows in the console, but the next line doesn't stop the timer.
clearInterval(intervalID);
}
}, [state.isRunning]);
完整代码:https://github.com/LazaroFilm/pomodoro
推荐答案
我认为你不需要为 intervalID使用
useState
和 useRef
钩子代码>.在 useEffect
之外声明它,但像这样清除 useEffect
钩子的清理函数中的间隔
I think you neither need to use useState
nor useRef
hooks for the intervalID
. Declare it outside the useEffect
but clear the interval in the cleanup function of the useEffect
hook like so
let intervalID;
useEffect(() => {
if (isRunning) {
intervalID = setInterval(() => {
dispatch({ type: "tic-toc" });
}, 1000);
}
return () => clearInterval(intervalID);
}, [isRunning]);
每当 isRunning
更改时,组件将卸载,并执行清理功能.因此,如果 isRunning
已更改为 false
那么计时器应该在卸载时停止,并且当它再次安装时,将不会满足 if 语句中的条件来运行setInterval,因此计时器保持停止状态.在我的代码中,我假设 isRunning
是布尔值(这是我喜欢的方式),并假设它是解构"的.来自 state
我假设来自 useReducer
钩子.
Whenever isRunning
changes the component will unmount, and the cleanup function will be executed. So, if the isRunning
has changed to false
then the timer should stop at the unmount, and when it's mounted again the condition in the if statement won't be met to run the setInterval, and thus the timer remains stopped. In my code I assumed isRunning
is boolean (which is the way I prefer it to be), and assumed it's "destructured" from the state
which I assume comes from useReducer
hook.
这篇关于clearInterval 不会在 useEffect 中停止我的计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!