我正在嘗試制作一個(gè)從 1.0 開(kāi)始并增加 0.1 直到達(dá)到隨機(jī)數(shù)的計(jì)時(shí)器。您必須在組件呈現(xiàn) 5 秒后啟動(dòng)“會(huì)話(huà)”,這一切都正常。問(wèn)題是我希望一個(gè)會(huì)話(huà)在另一個(gè)會(huì)話(huà)結(jié)束后 5 秒開(kāi)始,而 React 忽略了允許下一個(gè)會(huì)話(huà)的 setState,我不明白為什么。注意:只有當(dāng)我創(chuàng)建一個(gè)調(diào)用切換功能的按鈕 setIsGameActive(isGameActive => isGameActive = !isGameActive) 并單擊它時(shí)它才有效const GamePanel = () => { const [gameTime, setGameTime] = useState(1); const [isGameActive, setIsGameActive] = useState(false); const [gameEndTime, setGameEndTime] = useState(0); const [lastResults, setLastResults] = useState([]); let randomNumber = 0; const useFirstTime = useRef({firstTime: true}); const makeRandomNumber = (min, max) => { return min + (max - min) * Math.random() } onst reset = () => { setGameTime(1); setIsGameActive(false); //ignored } const gameStart = () => { if(useFirstTime.current.firstTime === false){ if(!isGameActive){ console.log("Game starting..."); randomNumber = makeRandomNumber(1.1, 5); setGameEndTime(randomNumber.toFixed(1)) setIsGameActive(true); } } } const gameFinished = () => { setTimeout(()=>{ reset(); gameStart() }, 5000) } useEffect(() => { if(useFirstTime.current.firstTime === true){ useFirstTime.current.firstTime = false; setTimeout(() => { gameStart(); }, 5000); } let interval = null; if(isGameActive){ interval = setInterval(() => { if(gameTime.toFixed(1) !== gameEndTime){ setGameTime(gameTime => gameTime + 0.1) } if(gameTime.toFixed(1) === gameEndTime){ clearInterval(interval) gameFinished(); } }, 100);
React SetState 被忽略
慕后森
2023-02-17 10:04:58