gpt4 book ai didi

reactjs - React 中的状态何时更新

转载 作者:行者123 更新时间:2023-12-03 14:18:08 26 4
gpt4 key购买 nike

我刚刚学习 React 并且正在做教程:https://reactjs.org/tutorial/tutorial.html

在其中,我们假设创建一个函数来计算 tic-tac-toe 的获胜者,并将方 block 内容的列表传递给它。每次单击一个方 block 时我都会更新此列表。但是,我注意到,当我使用 this.setState 设置 Board 对象的方 block 列表,然后尝试使用 this.state.squares 来设置它时,我没有得到事件状态,但前一个状态。

就像如果我在第一个方 block 中添加一个 X,它就会在下一步移动时出现在 this.state.squares 中。

这是代码,我使用:

handleClick(square){
let squares = this.state.squares.slice();
squares[square] = this.state.playing;
console.log(squares);
this.setState({squares: squares});
if(this.state.playing == 'X'){
this.state.playing = 'O';
}
else{
this.state.playing = 'X';
}
this.state.winner = calculateWinner(this.state.squares); #If I do that I get the previous state
this.state.winner = calculateWinner(squares); #If I do that I get the current state
}

为什么要这样做?

最佳答案

根据docs :

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

setState 是一种异步方法,它实际上意味着 handleClick 函数中的所有其他代码都将在 this.state.squares 发生变化之前执行.

但是您的代码中还存在另一个问题 - 您还尝试直接修改状态:

if(this.state.playing == 'X'){
this.state.playing = 'O';
}
else{
this.state.playing = 'X';

直接修改 this.state 不会重新渲染您的组件。

要解决这些问题,您可以使用 setState 回调:

this.setState({squares: squares}, () => {

if(this.state.playing == 'X'){
this.setState({"playing":"O"});
}
else{
this.setState({"playing":"X"});
}
// I'm assuming that `calculateWinner` does not depend on this.state.playing
this.setState({"winner":calculateWinner(this.state.squares));
});

只有在发生 this.state.squares 突变时才会调用 setState 回调 - 确保 this.state.squares 是在调用 calculateWinner 之前更新。

关于reactjs - React 中的状态何时更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53906386/

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