我正在尝试制作一个从 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);
开心每一天1111
相关分类