javascript - clearInterval 没有在 useEffect 中停止我的计数器
问题描述
我正在尝试在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]);
解决方案
我认为您既不需要使用useState
也不需要useRef
为intervalID
. 像这样在钩子的清理函数中声明它useEffect
但清除间隔useEffect
let intervalID;
useEffect(() => {
if (isRunning) {
intervalID = setInterval(() => {
dispatch({ type: "tic-toc" });
}, 1000);
}
return () => clearInterval(intervalID);
}, [isRunning]);
每当isRunning
发生更改时,组件将卸载,并且将执行清理功能。因此,如果isRunning
已更改为,false
则计时器应在卸载时停止,并且当再次安装时,将不满足 if 语句中的条件以运行 setInterval,因此计时器保持停止状态。在我的代码中,我假设isRunning
它是布尔值(这是我更喜欢的方式),并假设它是“解构”的state
,我假设它来自useReducer
钩子。
推荐阅读
- jmeter - 并发线程组和吞吐量整形计时器
- request - 为什么 npm install -g firebase-tools 请求已被弃用
- c# - 如何在不使用 iText7 和 C# 覆盖内容的情况下向现有 pdf 添加文本?
- android - 为什么我可以在 Android 主线程以外的线程中运行 UI 操作?
- django - django多数据库切换登录问题
- sas - 文字包含不匹配的引号
- bash - 在没有返回值时防止一元运算符预期的错误?
- java - itext7 pdfhtml 标题和屏幕阅读器有问题吗?
- openlayers - 升级后如何修复 OpenLayers 6 错误
- python - Boto3 备份服务员