如果使用 setState React.js,则 clearInterval 不起作用

clearInterval not working if using setState React.js

我正在使用 React 构建倒数计时器并遇到此问题:clearInterval works onCklick if it does not update the component。如果我在间隔函数 clearInterval 内更新状态,则不再清除间隔。我知道这与组件重新渲染有关?这是代码的相关部分。非常感谢您的建议:

const [sessionCount, setSessionCount] = useState(25);
const [timeLeft, setTimeLeft] = useState("25:00")

  
var timer ;
 
function startHandle() {
    let endTime = (sessionCount * 60000) + +new Date();
    timer = setInterval(function() {
        let diff = endTime - +new Date();
        const min = Math.floor(diff / 60000);
        const sec = Math.floor((diff / 1000) % 60);
        setTimeLeft(min + ":" + sec) //if this line is removed, then clearInterval works
    }, 1000)
};
function resetHandle() {
  setTimeLeft("25:00");
  clearInterval(timer);
};
<div id="time-display-container">
    <div id="timer-label">Session</div>
    <time id="time-left"></time>
    <button id="start_stop" onClick={startHandle}>start/stop</button>
    <button id="reset" onClick={resetHandle}>reset</button>
</div>

将计时器移到 App 组件之外。

import React, { useState } from "react";

let timer;


export default function App() {
  const [sessionCount, setSessionCount] = useState(25);
  const [timeLeft, setTimeLeft] = useState("25:00");


  function startHandle() {
    let endTime = sessionCount * 60000 + +new Date();
    timer = setInterval(function () {
      let diff = endTime - +new Date();
      const min = Math.floor(diff / 60000);
      const sec = Math.floor((diff / 1000) % 60);
      setTimeLeft(min + ":" + sec); //if this line is removed, then clearInterval works
    }, 1000);
  }

  function resetHandle() {
    setTimeLeft("25:00");
    clearInterval(timer);
  }

  return (
    <div id="time-display-container">
      <div id="timer-label">Session</div>
      <time id="time-left" />
      {timeLeft}
      <button id="start_stop" onClick={startHandle}>
        start/stop
      </button>
      <button id="reset" onClick={resetHandle}>
        reset
      </button>
    </div>
  );
}

另外,您检查计时器值以防止设置多个设置间隔。 我想在 useEffect 中定义这个计时器并在其他一些状态变化中调用它们会更具反应性,但上面的代码在 codesandbox

中对我有用