【发布时间】:2022-01-16 08:10:02
【问题描述】:
我有一个简单的掷骰子代码,我想根据掷骰子更新分数。
这是骰子的状态和分数:
const [Dice1, setDice1] = useState(0);
const [Dice2, setDice2] = useState(0);
const [Score1, setScore1] = useState(0);
const [Score2, setScore2] = useState(0);
function randomNum() {
setDice2(Math.floor(Math.random() * 6) + 1);
setDice1(Math.floor(Math.random() * 6) + 1);
Dice1 > Dice2 && Dice1 !== Dice2 ? setScore1(Score1 + 1) : Dice2 > Dice1 && Dice1 !== Dice2 ? setScore2(Score2 + 1) : setScore2(Score2 + 0);
}
函数 randomNum 在点击时触发。
return (
<div className="App">
<header className="App-header">
<p>Player 1 rolls {Dice1}</p>
<p>Player 2 rolls {Dice2}</p>
<button onClick={randomNum}>Roll the dice</button>
{Dice1 > Dice2 ? <p>Player 1 win</p> : Dice1 === Dice2 ? <p>Draw</p> : <p>Player 2 win</p>}
<p>Player 1 score is {Score1} points</p>
<p>Player 2 score is {Score2} points</p>
<button onClick={resetScore}>Reset score</button>
</header>
</div>
);
一切都很好,除了分数如果更新了 1 轮滞后。 每次我滚动时,都会添加上一轮的分数。 我在这里做错了什么?
【问题讨论】:
标签: reactjs use-state setstate