gpt4 book ai didi

reactjs - React useEffect 钩子(Hook)没有清除间隔

转载 作者:行者123 更新时间:2023-12-05 09:04:10 24 4
gpt4 key购买 nike

我正在尝试使用 react Hook 构建一个简单的倒数计时器来倒计时 3 秒。但是 3 秒后 UI 停止渲染但在 console.log 中我仍然可以每秒打印一次。为什么 useEffect 中的第二个数组参数不能阻止这种情况的发生?

code sandbox

function CounterGame() {
const [timeout, setTimeout] = React.useState(3);

React.useEffect(() => {
let id = window.setInterval(() => {
if (timeout > 0) {
setTimeout(x => x - 1 );
}
// this line keep executing even it timeout reach 0
console.log("in setInterval", timeout);
}, 1000)

return () => {
window.clearInterval(id);
}
}, [timeout])
return (
<div className="App">
See instructions.
<h1>{timeout} seconds</h1>
{!timeout && <button>Click</button>}
</div>
);
}

const rootElement = document.getElementById("root");
ReactDOM.render(<CounterGame />, rootElement);

最佳答案

这可能对你有用:

通过在useEffect中添加条件清除timeOut为零时的Intervel

React.useEffect(() => {
let id = window.setInterval(() => {
if (timeout > 0) {
setTimeout(x => x - 1 );
}

//clearIntervel here
if(timeout == 0){
window.clearInterval(id);
}

// this line keep executing even it timeout reach 0
console.log("in setInterval", timeout);
}, 1000)

return () => {
window.clearInterval(id);
}
}, [timeout])

关于reactjs - React useEffect 钩子(Hook)没有清除间隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68910950/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com