出于某种原因,我需要在前2分钟调用checkProgess
函数,并有10秒的延迟。
所以我就这样做了
const [timers, setTimers] = useState<ReturnType<typeof setTimeout>[]>([]);
useEffect(()=>{
for (let index = 0; index < 12; index++) {
const seconds = (index+1)*10000;
let timer = setTimeout(() => {
checkProgress(id, setFieldValue, contractType, fileOCRStatus);
}, seconds);
console.log("timer",timer)
setTimers((prev) => {
prev.push(timer)
return prev
});
}
},[])
在这12次尝试中,如果进度检查成功,这个组件将被卸载。2在这段时间里,我希望清除所有剩余的超时调用。3我在useEffect
返回函数中这样做了。
return () => {
console.log("Return function called",timers)
timers.forEach((timer) => clearTimeout(timer));
};
这部分执行成功,但清理的东西似乎不起作用。我可以看到API调用运行后,组件被卸载。
这里出了什么问题?在console.log("Return function called", timers)
中,计时器ID也可以正确打印。
1条答案
按热度按时间cbjzeqam1#
由于
useEffect
只运行一次,因此实际上不需要将它们存储在状态中(即使它没有运行,由于您正在清理返回函数中的计时器,因此不需要在渲染中保留该值)。