为什么一个简单的``usefeft''在扭曲“ setInterval/timeout”时不会采用更新值。里面
为什么一个简单的使用
在内部扭曲任何setInterval/timeout时不会采用更新值;
where variable stopped to initial value;
import { useState, useEffect } from "react";
let timerRef;
const StopWatch = () => {
const [time, setTime] = useState(0);
const [isPause, setPause] = useState(false);
useEffect(() => {
timerRef = setInterval(() => {
console.log({ time });
if (!isPause) {
setTime(time + 1);
}
}, 5000);
return () => clearInterval(timerRef);
}, []);
const startWatch = () => {
setPause(false);
};
const stopWatch = () => {
setPause(true);
};
return (
<>
time: {time}
<button onClick={startWatch}>Start</button>
<button onClick={stopWatch}>stop</button>
</>
);
};
export { StopWatch };
Why a simple useEffect
is not taking updated value when it is warping any setInterval/timeout inside;
where variable stopped to initial value;
import { useState, useEffect } from "react";
let timerRef;
const StopWatch = () => {
const [time, setTime] = useState(0);
const [isPause, setPause] = useState(false);
useEffect(() => {
timerRef = setInterval(() => {
console.log({ time });
if (!isPause) {
setTime(time + 1);
}
}, 5000);
return () => clearInterval(timerRef);
}, []);
const startWatch = () => {
setPause(false);
};
const stopWatch = () => {
setPause(true);
};
return (
<>
time: {time}
<button onClick={startWatch}>Start</button>
<button onClick={stopWatch}>stop</button>
</>
);
};
export { StopWatch };
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
通过时间的依赖,这应该有效
pass dependency of time and this should work
这是因为您正在访问
time
从关闭中访问值,并且由于您仅定义Settimeout处理程序一次(初始化),因此它将始终参考该初始值的time time
> 。我建议,对于此用例,仅将状态更新器与回调一起使用,并且它将为您提供机制,以轻松地使用Previos One更新状态,并且无法直接访问状态。只需重写settime(_time + 1)
tosettime(previme =&gt; previme + 1)
That is because you are accessing
time
value from the closure, and since you are defining setTimeout handler only once (on initialization) then it will always refer to that initial value fortime
. I suggest, for this use case, just to use state updater with callback, and like that it will provide you mechanism to easily update state with previos one, and by not accessing state directly. Just rewritesetTime(_time + 1)
tosetTime(prevTime => prevTime + 1)
CODESANDBOX已经警告过您。
CodeSandbox already warned you about that.