我正在尝试在React 钩子中使用 asetInterval
和 a 。计时器按预期启动,但不会停止。我分配给然后打电话clearInterval
useEffect
setInterval
intervalID
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]);