如何在单击按钮时清除反应钩子中的间隔

use*_*981 2 javascript timer reactjs react-hooks

我正在构建一个带有反应钩子的简单计时器。我有两个按钮启动和重置。当我单击开始按钮时,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>
);
}
Run Code Online (Sandbox Code Playgroud)

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

Shu*_*tri 6

您可以在 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>
);
}
Run Code Online (Sandbox Code Playgroud)