问题
I have this code in React, where I would like a count down session/break timers to alternate when the clock on the screen reaches 0. The problem I am having is that when I don't include clockTime
as a dependency in the useEffect
hook function, the timers count every 1 second correctly (I suppose), however, the clockTime
state variable isn't updated, so the current clock time will never be 0, and the current session will keep counting down below 0. On the other hand, when I include clockTime
as a dependeny, then the clockTime
state variable is updated, and it reaches 0, and the sessions/breaks timers alternate, but with a higher rate than 1 second. How can I solve this problem, by making the sessions/breaks timers alternate and run at a rate of 1 second?
import React, { useState, useEffect } from 'react';
import './App.css';
function App() {
const [sessionTime, setSessionTime] = useState(10);
const [breakTime, setBreakTime] = useState(5);
const [clockTime, setClockTime] = useState(10);
const [current, setCurrent] = useState('session');
const [isPlaying, setIsPlaying] = useState(false);
useEffect(() => {
if (isPlaying) {
let startTime = new Date();
const intervalId = setInterval(() => {
if (clockTime === 0) {
setCurrent(current === 'session' ? 'break' : 'session');
setClockTime(current === 'session' ? breakTime : sessionTime);
} else {
setClockTime(
(clockTime) =>
clockTime +
Math.floor((startTime.getTime() - new Date().getTime()) / 1000)
);
}
}, 200);
return () => {
clearInterval(intervalId);
};
}
}, [isPlaying, clockTime]);
const handlePlayClick = () => {
setIsPlaying(true);
};
const handlePauseClick = () => [setIsPlaying(false)];
return (
<div className='App'>
<span>{clockTime}</span>
<span>{current}</span>
{isPlaying ? (
<button onClick={handlePauseClick}>Pause</button>
) : (
<button onClick={handlePlayClick}>Play</button>
)}
</div>
);
}
export default App;
来源:https://stackoverflow.com/questions/63936170/problem-with-updating-the-state-in-useeffect-when-dependencies-are-included