JavaScript清除超时不适用于React useEffect返回函数

gupuwyp2  于 2023-02-11  发布在  Java
关注(0)|答案(1)|浏览(86)

出于某种原因,我需要在前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也可以正确打印。

cbjzeqam

cbjzeqam1#

由于useEffect只运行一次,因此实际上不需要将它们存储在状态中(即使它没有运行,由于您正在清理返回函数中的计时器,因此不需要在渲染中保留该值)。

// delete the useState stuff

useEffect(() => {
  const timers = [];
  for (let index = 0; index < 12; index++) {
    const seconds = (index+1)*10000;
    
    const timer = setTimeout(() => {
      checkProgress(id, setFieldValue, contractType, fileOCRStatus);
    }, seconds);
    console.log("timer",timer)
    timers.push(timer);
  }

  return () => {
    timers.forEach((timer) => clearTimeout(timer));
  }
}, []);

相关问题