如何在React中清除间隔

问题描述 投票:1回答:1

我正在使用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>
  );
}

javascript reactjs babel
1个回答
0
投票

在函数组件内部声明变量将在每次呈现组件时运行。您需要在useState中捕获间隔,例如

var [intervalState, setIntervalState] = useState(null)

...

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

   setIntervalState(clearInterval)
}

这将确保您的clearInterval值在所有转售中都将持续存在

© www.soinside.com 2019 - 2024. All rights reserved.