使用setInterval

时间:2020-09-17 14:01:36

标签: javascript reactjs setinterval setstate

我使用类组件制作了Pomodore计时器。现在,我想将其转换为功能组件。 这是我目前所拥有的。

function App() {
  const [time, setTime] = useState(null);
  const [isRunning, setIsRunning] = useState(false);
  const [session, setSession] = useState("work");
  const [countdownID, setCountdownID] = useState(null);
  const [streak, setStreak] = useState(0);
  // TODO - settings
  const [workTime, setWorkTime] = useState(10);
  const [breakTime, setBreakTime] = useState(5);
  const [longBreakTime, setLongBreakTime] = useState(20);

  // USE EFFECTS
  useEffect(() => {
    setTime(workTime);
  }, []);

  // FUNCTIONS
  const counter = () => {
    if (time === 0) {
      if (session === "work") {
        if (streak < 3) {
          setTime(breakTime); // short break
          setSession("break");
          setStreak((streak) => streak + 1);
        } else {
          setTime(longBreakTime); // long break
          setSession("break");
          setStreak(0);
        }
      } else if (session === "break") {
        stopCounter();
        setTime(workTime);
        setSession("work");
      }
    } else {
      setTime((time) => time - 1);
    }
    console.log(time);
  };

  const startCounter = () => {
    let countdownID = setInterval(counter, 1000);
    setCountdownID(countdownID);
    setIsRunning(true);
  };

  const stopCounter = () => {
    clearInterval(countdownID);
    setIsRunning(false);
  };

  const resetCounter = () => {
    if (session === "work") {
      clearInterval(countdownID);
      setTime(workTime);
      setSession("break");
      setIsRunning(false);
    } else {
      // skipping break
      clearInterval(countdownID);
      setTime(workTime);
      setSession("work");
      setIsRunning(false);
    }
  };

  return (
    <>
      <Timer
        time={time}
        isRunning={isRunning}
        startCounter={startCounter}
        stopCounter={stopCounter}
        resetCounter={resetCounter}
      />
      <Streak streak={streak} />
    </>
  );
}

export default App;

问题在于setTime((time) => time - 1);似乎无法按预期工作,并且仅更新Timer组件中Timer的可视表示。倒计时也不会在00:00停止,并且negative numbers会显示出来。这可能是因为当我console.log(time)时,我总是得到最初的10,这是使用useEffect分配的。如何使setTime正确更新状态?

0 个答案:

没有答案
相关问题