【问题标题】:The clearInterval() function doesn't clear Interval In ReactclearInterval() 函数不会清除 React 中的 Interval
【发布时间】:2021-07-05 14:57:29
【问题描述】:

我正在这样做:

startinterval = () => {
    this.interval = setInterval(this.intervalFunction, 10000)
}


clearInterval = () => {
    clearInterval(this.interval)
}

但是当我调用 clearInterval 函数时,它什么也不做,并且间隔继续

【问题讨论】:

  • 您如何在单击按钮或|| 时调用clearInterval() 函数?!!向我们展示更多代码
  • 两个函数中的this 是指同一个对象吗?很有可能,它没有。

标签: javascript reactjs next.js


【解决方案1】:

如果您使用的是功能组件,您可以使用:

function MyComponent() {
  const [intervalId, setIntervalId] = useState();

  useEffect(() => {
    let id = setInterval(() => {
      //Code to do
    }, 10000);
    setIntervalId(id);

    return () => {
      clearInterval(intervalId);
    };
  });

  return <div>UI Here</div>;
}

如果您使用类作为组件:

class MyComponent {
    intervalId;

  componentDidMount() {
    this.intervalId = setInterval(() => {
        //Code to do here or call another function
    }, 10000);
  }

  componentWillUnmount() {
      clearInterval(this.intervalId);
  }
}

提前采取的最重要的事情是您需要存储 id 以清除超时。如果您丢失了正确的 id,则清除功能将无法正常工作。

【讨论】:

  • omg 非常感谢你,我缺少的是组件中的intervalId;
猜你喜欢
  • 2023-02-20
  • 2021-12-15
  • 2021-04-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-14
  • 2012-05-13
  • 2020-01-12
相关资源
最近更新 更多