[英]React useEffect and clearInterval
I have a button that toggles the state named start
from true to false.我有一个按钮可以将名为
start
的状态从真切换为假。 if true U want to see the console log, as soon as I press stop I want the log to stop.如果是真的,你想查看控制台日志,只要我按下停止,我就希望日志停止。
useEffect(() => {
let timePassed = 0;
let timeLeft = timeLimit;
if (start) {
const timerInterval = setInterval(() => {
timePassed += 1;
if (!start) {
console.log('stop')
clearInterval(timerInterval);
}
console.log('start')
}, 100);
}
}, [start]);
The console never stop logging start
控制台永不停止记录
start
The local variable start
is never going to change, even if you call setStart
.局部变量
start
永远不会改变,即使你调用setStart
。 Calling setStart
is just an instruction to react to render the component again.调用
setStart
只是一个指令来重新渲染组件。 On that new render a new local variable will be created with start equal to false, but the effect from the previous render is never going to see that.在那个新的渲染上,一个新的局部变量将被创建,start 等于 false,但是之前渲染的效果永远不会看到。
Instead, what you need is to return a teardown function.相反,您需要的是返回一个拆卸函数。 When the effect is called for a second time, react will call the previous time's teardown function.
当效果第二次调用时,react 会调用上一次的teardown 函数。
useEffect(() => {
let timePassed = 0;
let timeLeft = timeLimit;
if (start) {
const timerInterval = setInterval(() => {
timePassed += 1;
console.log('start')
}, 100);
return () => {
console.log('stop')
clearInterval(timerInterval);
}
}
}, [start])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.