我希望倒计时完成时显示一条消息。 我正在尝试使用从 App.jsx 传递给 Timer.jsx 组件的 onComplete 函数来做到这一点。 该函数在 useEffect 钩子中执行:
第一个 useEffect 是设置从 App.jsx 的输入接收的时间。 第二个 useEffect 是减去倒计时值并检查倒计时是否已达到 0。
code snippet start
useEffect(()=>{
setCountdown(duration);
}, [duration])
useEffect(() => {
if (countdown === 0 && isTimerRunning) {
console.log("reached complete")
onComplete();
return;
}
if(countdown <= 0){
return;
}
const timerId = setTimeout(() => {
setCountdown((prev) => prev - 1000);
}, 1000);
return () => clearInterval(timerId);
}, [countdown, onComplete, isTimerRunning])
code snippet end
问题是当我设置输入的日期并单击开始按钮时, 立即显示已完成的消息,并且计时器不会启动,因为“倒计时<= 0 && isTimerRunning" condition is met even before the countdown is set.
项目链接:application_link
我希望倒计时完成后显示该消息。
嗨,我发现 startCountdown 函数存在问题
尝试用下面的这些函数替换它
function startCountdown(time) {
const selectedDateTime = new Date(time);
const currentTime = new Date();
const timeDifference = selectedDateTime.getTime() - currentTime.getTime();
return timeDifference > 0 ? timeDifference : 0;
}
useEffect(() => {
if (isTimerRunning) {
const timerDuration = startCountdown(time);
if (timerDuration === 0) {
// Timer has reached 0, handle completion
handleTimerComplete();
} else {
setMilliseconds(timerDuration);
}
}
}, [time, isTimerRunning]);
通过此调整,计时器现在应该从所选时间开始倒计时。当它达到0时,它将调用handleTimerComplete来显示完成消息。
希望这有帮助