我正在尝试制作一个从 1.0 开始并增加 0.1 直到达到随机数的计时器。您必须在组件呈现 5 秒后启动“会话”,这一切都正常。问题是我希望一个会话在另一个会话结束后 5 秒开始,而 React 忽略了允许下一个会话的 setState,我不明白为什么。注意:只有当我创建一个调用切换功能的按钮 setIsGameActive(isGameActive => isGameActive = !isGameActive) 并单击它时它才有效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);
1 回答
开心每一天1111
TA贡献1836条经验 获得超13个赞
每次渲染组件时都会创建重置函数。因此,计时器内部的重置引用与重新渲染后的组件本身不同。尝试使用useCallback重置来创建函数的记忆版本:https://reactjs.org/docs/hooks-reference.html#usecallback
const reset = useCallback(() => {
setGameTime(1);
setIsGameActive(false); //ignored
},[])
添加回答
举报
0/150
提交
取消