我制作了一个基本的幻灯片演示,其中选中复选框幻灯片已启用。问题是,一旦启用幻灯片放映,即使我取消选中该复选框,也无法禁用它。据了解,我正在学习计时器,并取消存储计时器的状态,但幻灯片继续播放。
具体来说,这部分在复选框更新时被调用:
useEffect(() => {
if (isTrue) {
setSlideTimer(() => {
return setInterval(() => {
forwardButton.current.click();
}, slideDuration);
});
} else {
clearInterval(slideTimer);
setSlideTimer(null);
}
}, [isTrue]);
从浏览器日志中可以明显看出计时器确实被清除了。虽然有警告"... component is changing an uncontrolled input of type checkbox to be controlled"
但我不确定这是否是罪魁祸首。
最佳答案
问题
问题在于您缺少对 sliderTimer
状态的依赖。
useEffect(() => {
if (isTrue) {
setSlideTimer(() => {
return setInterval(() => {
forwardButton.current.click();
}, slideDuration);
});
} else {
clearInterval(slideTimer);
setSlideTimer(null);
}
}, [isTrue]);
解决方案
通常不要将计时器 ID 存储在状态中。如果您需要在 useEffect
钩子(Hook)外部访问计时器 ID,请使用 React ref,否则只需将其缓存在 useEffect
钩子(Hook)的回调中本地即可。在这种情况下,您将需要使用 ref 来保存 sliderTimer
id 值,以便在组件卸载时也可以清除它。
示例:
const sliderTimerRef = React.useRef();
useEffect(() => {
// Clear any running intervals on component unmount
return () => clearInterval(sliderTimerRef.current);
}, []);
useEffect(() => {
if (isTrue && forwardButton.current) {
sliderTimerRef.current = setInterval(
forwardButton.current.click,
slideDuration
);
} else {
clearInterval(sliderTimerRef.current);
}
}, [isTrue]);
其他问题
From browser logs it is evident that timer indeed got cleared. Though there is a warning
"... component is changing an uncontrolled input of type checkbox to be controlled"
but I'm not sure if that's the culprit here.
当 value
或 checked
属性从未定义值更改为已定义值时,通常会出现这种情况。确保无论检查的状态是什么,它都是最初定义的,即使只是 false
。
关于javascript - react : Setinterval is not stopping even after clearing the timer using clearInterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71847441/