如何清除 React 中的间隔

How to clear the interval in React

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

这是我的代码:

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>
  );
}

在函数组件中声明一个变量将在每次渲染组件时运行。您需要在

这样的 useState 中捕获间隔
var [intervalState, setIntervalState] = useState(null)

...

function onStart() {
   var clearInterval = setInterval(() => {
      ...
   })

   setIntervalState(clearInterval)
}

这将确保您的 clearInterval 值将在重新渲染中保持不变

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

总之,你开始思考钩子就好了:)

更简洁的方法是实现类似 useInterval:

的方法
const [isRunning, setIsRunning] = useState(true)

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

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

Here 是一个实际实现挂钩的演示。