简体   繁体   English

clearInterval() function 不会清除 React 中的 Interval

[英]The clearInterval() function doesn't clear Interval In React

Im doing this:我这样做:

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


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

but when i call the clearInterval function it doesn't do anything and the interval continues但是当我调用clearInterval function 它什么也没做并且间隔继续

If you are using functional components you can use:如果您使用的是功能组件,您可以使用:

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

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

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

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

If you are using a class as component:如果您使用 class 作为组件:

class MyComponent {
    intervalId;

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

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

The best important to take in advance is that you need store the id for clear the timeout.提前采取的最重要的事情是您需要存储 id 以清除超时。 If you lost the correct id the clear function won't work correctly.如果您丢失了正确的 ID,则清除 function 将无法正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM