I am just learning React and I was doing the tutorial : https://reactjs.org/tutorial/tutorial.html
In it, we are suppose to create a function that calculate the winner of the tic-tac-toe and we pass to it the list of the squares' contents. I update this list each time a square is clicked. However, I noticed that when I use this.setState
to set the squares list of my Board object and then try to have it with this.state.squares
I do not get the active state but the previous one.
Like if I add an X in the first square, it will be in this.state.squares
at the next move.
Here is the code, I use :
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
}
Why does it do that ?