达到给定值时取消间隔

时间:2019-05-08 00:46:28

标签: reactjs react-hooks

当我的App中的progressState大于99时,我应该在哪里放置clearInterval?

  const [progressState, setProgress] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => { setProgress(progressState => progressState + 1);}, 1000);
  }, []); // this is only called once because of [], now i can't check for clearing

由于函数式编程,我感到困惑,即使加1 + 1也成为噩梦。

我是否必须使用另一种useEffect方法清除间隔?

我现在这样做了


  const [progressState, setProgress] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setProgress(progressState => {
        progressState == 100 && clearInterval(interval)
        return progressState + 1;
      });
    }, 100);
  }, []);

1 个答案:

答案 0 :(得分:0)

在处理程序函数中。

const interval = setInterval(() => {
  setProgress(progressState => progressState + 1);
  if (progressState >= 99) {
    clearInterval(interval);
  }
}, 1000);