[英]Get .current value in useRef
I have a start/stop timer function that will start or stop the timer.我有一个启动/停止计时器功能,可以启动或停止计时器。 It works perfectly but I'm trying to have it stop at 30 seconds and run saveTrial()
.它运行良好,但我试图让它在 30 秒停止并运行saveTrial()
。 I've tried console logging timer.current
and time
at various locations, but neither are representing what the current timer is showing in seconds.我已经尝试过在不同位置记录timer.current
和time
控制台,但都没有代表当前计时器以秒为单位显示的内容。
const [time, setTime] = useState(0);
let timer = useRef(0);
const startStopTimer = () => {
if (!timer.current)
timer.current = setInterval(() => {
setTime(time => time + 1);
}, 1000);
} else {
clearInterval(timer.current);
timer.current = 0;
}
};
Including time
in useEffect as a dependency works perfectly.在 useEffect 中包含time
作为依赖项非常有效。
useEffect(() => {
if (time === 10) {
saveTrial();
};
}, [time]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.