[英]Refreshing and updating useState/useRef in React
嘗試更新和讀取 React 中的狀態以在兩個不同的計時器之間切換。 我還是編程新手,無法弄清楚為什么顯示狀態“會話”或“中斷”的組件會更新,但我的條件 switchTimers() 無法根據該狀態切換計時器。
const [timers, setTimers] = useState({
sessionTime: 25,
breakTime: 5,
});
const [timerDisplay, setTimerDisplay] = useState("Session");
const [timerActive, setTimerActive] = useState(false)
const [displayCount, setDisplayCount] = useState(1500);
const round = useRef();
function startStop(action, secondsLeft) {
const interval = 1000;
let expected = Date.now() + interval;
if (action === "start") {
setTimerActive(true)
round.current = setTimeout(step, interval);
function step() {
if (secondsLeft > 0) {
const drift = Date.now() - expected;
setDisplayCount((prevValue) => prevValue - 1);
secondsLeft --
expected += interval;
round.current = setTimeout(step, Math.max(0, interval - drift));
} else {
clearTimeout(round.current)
switchTimers()
}
}
} else if (action === "stop") {
clearTimeout(round.current);
setTimerActive(false);
}
}
function switchTimers() {
beep.current.play()
if (timerDisplay === "Session") {
setTimerDisplay("Break");
setDisplayCount(timers.breakTime * 60);
startStop("start", timers.breakTime * 60)
} else if (timerDisplay === "Break") {
setTimerDisplay("Session");
setDisplayCount(timers.sessionTime * 60);
startStop("start", timers.sessionTime * 60)
}
}
當“會話”計時器結束時,它會在我打印timerDisplay的標簽中顯示“中斷”,但是一旦“中斷”計時器結束,它會重新運行“中斷”而不是切換到“會話”。 對出了什么問題有任何見解嗎?
嘗試將整個 switchTimers 函數編寫為useEffect掛鈎的回調,並將 timerDisplay 添加為依賴項。 另外,請顯示您從組件返回的 JSX,即整個代碼,以便我可以更好地幫助您。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.