首页 > 解决方案 > 如何使用钩子定期触发功能,当满足某些条件时,我想清除时间间隔?

问题描述

我有一个反应组件,它在安装后定期执行某个任务。但是我想在满足标准后清除一次间隔。我怎样才能做到这一点?

我的代码

const [totalTime, setTotalTime] = React.useState(10000);

const foo = () => {
      console.log("Here");
  };

React.useEffect(() => {
    const secondInterval = setInterval(() => {
      if (totalTime > 0) setTotalTime(totalTime - 1000);
    }, 1000);
    return () => clearInterval(secondInterval);
  });

React.useEffect(() => {
    let originalInterval;
    if (totalTime > 0)
      originalInterval = setInterval(() => {
        foo();
        console.log(totalTime);
      }, 5000);
    return () => clearInterval(originalInterval);
  }, []);

当我在 10000 毫秒后观看控制台时,它仍在记录此处,并且时间始终为 10000 毫秒。我无法弄清楚到底发生了什么。

标签: javascriptreactjsreact-hooks

解决方案


您可能需要将旧状态作为参数传递给setTotalTime更新程序函数。您还可能需要将(另一个)状态变量作为依赖项传递给useEffect钩子,以便在每次状态变量更改时执行该函数

React.useEffect(() => {
    const secondInterval = setInterval(() => {
      if (totalTime > 0) setTotalTime(totalTime => totalTime - 1000);
    }, 1000);
    return () => clearInterval(secondInterval);
  }, [...]);

推荐阅读