我在React中有这段代码,我想在屏幕上的时钟达到0时倒计时会话/中断计时器。我遇到的问题是当我不包括clockTime
时作为useEffect
钩子函数的依赖项,计时器正确地每1秒计数一次(我想),但是clockTime
状态变量不会更新,因此当前时钟时间永远不会为0,并且当前会话将继续递减计数到0以下。另一方面,当我将clockTime
作为依赖项时,clockTime
状态变量将更新,并达到0,会话/中断计时器交替出现,但速率高于1秒。如何通过使会话/中断计时器交替 并以1秒的速度运行来解决此问题?
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;