gpt4 book ai didi

javascript - react native : setState did not update immediately

转载 作者:行者123 更新时间:2023-12-04 17:13:06 27 4
gpt4 key购买 nike

我正在尝试为 Android 应用程序制作 TicTacToe 游戏。我打算做的井字游戏的游戏模式是人机对战。但问题是程序没有更新我的 switchPlayer 函数中的切换过程 (setState),因为执行 setState 后,前一个播放器和当前播放器是相同的。 switchPlayer 函数的预期输出:前一个玩家:1,当前玩家:-1 但实际输出:前一个玩家:1,当前玩家:1。

我也尝试使用其他 Stackoverflow 问题建议/推荐的回调方法,但仍然无法正常工作。我做对了吗?任何建议将不胜感激。提前谢谢你。

代码如下:

switchPlayer = (newPlayer) => {
console.log("Previous player: "+this.state.currentPlayer);
this.setState(

{currentPlayer: newPlayer},
function () {console.log("Current player: "+this.state.currentPlayer); }

);
};

onTilePress = (row, col, ValidMove) => {

if (ValidMove == 1) { //If move is valid

//Dont allow tiles to change
var value = this.state.gameState[row][col];
if (value !== 0) { return;}

//Identify and grab current player
var PlayerNow = this.state.currentPlayer;

console.log(row, col, PlayerNow);
//Set the correct tile...
var arr = this.state.gameState.slice();
arr[row][col] = PlayerNow;
this.setState({gameState: arr});

//Switch to other player
if (PlayerNow == 1) { //if player 1, then change to bot
this.switchPlayer(-1);
}
else if (PlayerNow == -1) {
this.switchPlayer(1);
}

console.log("New current player " + this.state.currentPlayer);

//check winner
var winner = this.getWinner(); //get the winner update
if (winner == 1) {
Alert.alert("Player 1 has won!");
this.initializeGame();
}
else if (winner == -1){
Alert.alert("Bot has won!");
this.initializeGame();
}
else if (this.checkTie() == 9){ //check if the match is a draw
Alert.alert("It's a draw!");
this.initializeGame();
}
//Alert.alert("It's Player "+takePlayer+"'s turn!");
this.BotMove();
}
else {
Alert.alert("Player 1, please make a move!");
}

}

最佳答案

如果您的问题是您希望在调用 switchPlayer() 之后的日志语句已经包含状态更改...那么您必须在调用 switchPlayer< 之后放置所有内容 在已通过 switchPlayer

传播的回调中
switchPlayer = (newPlayer, cb) => {
console.log("Previous player: "+this.state.currentPlayer);
this.setState(
{currentPlayer: newPlayer},
function () {
console.log("Current player: "+this.state.currentPlayer);
// Callers should put their code
if (cb) {
cb();
}
}
);
};

onTilePress = (row, col, ValidMove) => {
// Switch to other player
if (PlayerNow == 1) { //if player 1, then change to bot
this.switchPlayer(-1, () => {
// Here, you know the state has been updated
});
}
else if (PlayerNow == -1) {
....
}
// This code executes before the state is changed, you get the old state
// All your code should really be in the callbacks to `switchPlayer`
// or to any method that calls `setState`
console.log("New current player " + this.state.currentPlayer);
...
}

关于javascript - react native : setState did not update immediately,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69130881/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com