【问题标题】:how to clearInterval in react hook on clicking button如何在单击按钮时在反应挂钩中清除Interval
【发布时间】:2020-09-25 19:22:51
【问题描述】:

我正在构建一个带有反应钩子的简单计时器。我有两个按钮启动和重置。 当我单击开始按钮时,handleStart 函数工作正常,计时器启动,但我不知道如何在单击重置按钮时重置计时器。 这是我的代码

const App = () => {
  const [timer, setTimer] = useState(0)

  const handleStart = () => {
   let increment = setInterval(() => {
   setTimer((timer) => timer + 1)
  }, 1000)
}

const handleReset = () => {
  clearInterval(increment) // increment is undefined
  setTimer(0)
}

return (
  <div className="App">
    <p>Timer: {timer}</p>
    <button onClick={handleStart}>Start</button>
    <button onClick={handleReset}>Reset</button>
  </div>
);
}

为了停止或重置计时器,我需要在 clearInterval 方法中传递一个属性。增量是在 handleStart 函数中定义的,所以我无法在 handleReset 函数中访问它。怎么办?

【问题讨论】:

  • 有什么妨碍你在全球范围内定义它吗?

标签: javascript reactjs timer react-hooks


【解决方案1】:

您可以在 ref 中设置 timerId 并在您的 handleReset 函数中使用它。目前,增量值对您来说是未定义的,因为您已在 handleStart 函数中声明它,因此如果仅限于此函数,则变量的范围。

您也不能直接在 App 组件中将其定义为变量,因为它会在 App 组件重新渲染时重置。这就是 ref 派上用场的地方。

下面是一个示例实现

const App = () => {
  const [timer, setTimer] = useState(0)
  const increment = useRef(null);
  const handleStart = () => {
   increment.current = setInterval(() => {
   setTimer((timer) => timer + 1)
  }, 1000)
}

const handleReset = () => {
  clearInterval(increment.current);
  setTimer(0);
}

return (
  <div className="App">
    <p>Timer: {timer}</p>
    <button onClick={handleStart}>Start</button>
    <button onClick={handleReset}>Reset</button>
  </div>
);
}

【讨论】:

  • 今天也谢谢你
【解决方案2】:

为什么不直接使用钩子功能呢?

定义interval 状态,就像定义timer 状态一样。

const [intervalval, setIntervalval] = useState()

现在您在handleStart 中设置状态,并且在clearinterval 中您将可以访问修改后的状态。

const handleStart = () => {
   let increment = setInterval(() => {
       setTimer((timer) => timer + 1)
   }, 1000);
   setIntervalval(increment);
}


const handleReset = () => {
      clearInterval(intervalval);
      setTimer(0);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 2020-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-04
    • 2020-08-26
    相关资源
    最近更新 更多