首页 > 解决方案 > 如何清除 React 中的间隔

问题描述

我正在通过useState在 react.js 中使用钩子来构建秒表,但是在实现暂停功能时,我注意到我无法清除间隔。我是新手,我尝试了很多东西,但仍然没有用。如果有人可以帮助我修复代码或建议我以其他方式。

这是我的代码:

function App() {
  const [stopwatch, setStopwatch] = useState({
    hour: 0,
    min: 0,
    sec: 0,
    secElapsed: 0,
    minElapsed: 0,
  });

  const [buttonState, setButtonState] = useState({
    start: true,
    stop: false,
    pause: false,
    resume: false,
  });

  var interval = null;

  function onStart() {
    // i want to clear this interval when the onPause function is called
    var clrInt = setInterval(() => {
      setStopwatch(prevValue => {
        prevValue.secElapsed++;
        return {
          hour: Math.floor(prevValue.secElapsed / 3600),
          minElapsed: Math.floor((prevValue.secElapsed + 1) / 60),
          min: prevValue.minElapsed % 60,
          sec: prevValue.secElapsed % 60,
          secElapsed: prevValue.secElapsed,
        };
      });
    }, 1000);

    setButtonState(prevValue => {
      return {
        ...prevValue,
        start: false,
        pause: true,
        stop: true,
      };
    });
    interval = clrInt;
  }

  function onPause() {
    setButtonState(prevValue => {
      return {
        ...prevValue,
        pause: false,
        resume: true,
      };
    });

    // i want to clear the interval in onStart function here
    clearInterval(interval);
  }

  return (
    <div>
      <h1>
        {stopwatch.hour < 10 ? '0' + stopwatch.hour : stopwatch.hour}:
        {stopwatch.min < 10 ? '0' + stopwatch.min : stopwatch.min}:
        {stopwatch.sec < 10 ? '0' + stopwatch.sec : stopwatch.sec}
      </h1>
      {buttonState.start ? <button onClick={onStart}>Start</button> : null}
      {buttonState.pause ? <button onClick={onPause}>Pause</button> : null}
      {buttonState.stop ? <button>Stop</button> : null}
      {buttonState.resume ? <button>Resume</button> : null}
    </div>
  );
}

标签: javascriptreactjsbabeljs

解决方案


我认为间隔不适合组件的状态。相反,我会使用useRef钩子在组件的整个生命周期中保持它。

无论如何,你开始思考钩子很好:)

一种更简洁的方法是实现类似useInterval的东西:

const [isRunning, setIsRunning] = useState(true)

useInterval(() => {
    // Your custom logic here
}, isRunning ? 1000 : null)

const onPause = () => {
    // ...
    setIsRunning(false)
}

是一个实际实现钩子的演示。


推荐阅读