【发布时间】:2021-08-24 16:30:17
【问题描述】:
我正在尝试使用反应挂钩构建一个简单的倒计时计时器来倒计时 3 秒。但是 3 秒后 UI 停止渲染,但在 console.log 中我仍然可以每秒打印出来。为什么useEffect中的第二个数组参数不能阻止这种情况的发生?
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);
【问题讨论】:
标签: reactjs