我正试图通过重写"Rock Paper Scissor"游戏来学习React.js中的钩子。当我按下选择按钮时,我无法同时评估获胜者。这是我的代码(这是一个较短的代码,我只比较按下纸张按钮的玩家(:
function App() {
const weapons = ["paper","scissors","rock"];
const [choice, setChoice] = useState({
playerOne: "",
playerTwo: "",
winner: ""
})
const chooseWeapon=(weapon)=>{
setChoice({
playerOne: weapon,
playerTwo: weapons[Math.floor(Math.random() * 3)],
winner: getWinner(choice.playerOne,choice.playerTwo)
})
}
const getWinner = (player1,player2)=>{
if(player1==="paper"){
if(player2==="scissors"){
return("player two won")
} else if(player2==="rock"){
return("player one won!!!!!")
}
}
}
return (
<div className="App">
<h1>Rock scissors lizard</h1>
<h2>player one:{choice.playerOne}</h2>
<h2>player two:{choice.playerTwo}</h2>
<h1>{choice.winner}</h1>
<button onClick={()=>chooseWeapon("paper")}>paper</button>
<button onClick={()=>chooseWeapon("scissors")}>scissors</button>
<button onClick={()=>chooseWeapon("rock")}>rock</button>
</div>
);
}
export default App;
基本上,当我点击"纸"按钮时,我会在每个玩家的屏幕选择上进行渲染,但只有再次按下后,我才会获得获胜者状态。获胜的渲染总是落后一步。我该怎么解决这个问题?
谢谢你们!
状态更新不会立即发生,而是在下一个渲染周期中发生,因此,当您预计获胜者变量将根据玩家1和玩家2的选择进行评估时,它实际上是基于以前的值。要解决这个问题,您需要首先计算获胜者,然后将其设置为状态
function App() {
const weapons = ["paper","scissors","rock"];
const [choice, setChoice] = useState({
playerOne: "",
playerTwo: "",
winner: ""
})
const chooseWeapon=(weapon)=>{
const choiceP1 = weapon;
const choiceP2 = weapons[Math.floor(Math.random() * 3)];
const winner = getWinner(choiceP1, choiceP2)
setChoice({
playerOne: choiceP1,
playerTwo: choiceP2,
winner,
})
}
const getWinner = (player1,player2)=>{
if(player1==="paper"){
if(player2==="scissors"){
return("player two won")
} else if(player2==="rock"){
return("player one won!!!!!")
}
}
}
return (
<div className="App">
<h1>Rock scissors lizard</h1>
<h2>player one:{choice.playerOne}</h2>
<h2>player two:{choice.playerTwo}</h2>
<h1>{choice.winner}</h1>
<button onClick={()=>chooseWeapon("paper")}>paper</button>
<button onClick={()=>chooseWeapon("scissors")}>scissors</button>
<button onClick={()=>chooseWeapon("rock")}>rock</button>
</div>
);
}
export default App;
在传递参数以确定游戏获胜者的函数中:
setChoice({
playerOne: weapon,
playerTwo: weapons[Math.floor(Math.random() * 3)],
winner: getWinner(choice.playerOne,choice.playerTwo)
})
这里,您所指的choice.playerOne
和choice.player2
尚未设置。您需要做的是传入playerOne和playerTwo的当前选择。
const playerOne = weapon;
const playerTwo = weapons[Math.floor(Math.random() * 3)];
setChoice({
playerOne,
playerTwo,
winner: getWinner(playerOne, playerTwo),
})