我正在尝试在练习 Hooks 时实现一个简单的计数器:
function App() {
const cpuWeapon = ["paper", "rock", "scissor"];
const [playerChoice, setPlayerChoice] = useState({
playerOne: {
choice: "",
score: 0
},
playerTwo: {
choice: "",
score: 0
}
});
const { playerOne, playerTwo } = playerChoice;
const selectWeapon = weapon => {
const player1 = weapon;
const player2 = cpuWeapon[Math.floor(Math.random() * 3)];
setPlayerChoice({
playerOne: {
choice: player1,
score: getScore(player1, player2)
},
playerTwo: {
choice: player2,
score: getScore(player1, player2)
}
});
};
const getScore = (pl1, pl2) => {
if (pl1 === "paper") {
if (pl2 === "scissor") {
return playerTwo.score + 1;
} else if (pl2 === "rock") {
return playerOne.score + 1;
}
}
};
}
这里的问题是,即使我在返回时指定了不同的对象,我也会 在组件 render 时对两个分数进行相同的更新。
我该如何克服呢?
在那些有反应的情况下,哪种方法最好?
慕村225694
忽然笑
相关分类