1
votes

Hi so here is the situation. I am building a tictactoe game with react and I have 3 components 1. GameParent 2. board 3. gameControls

I have a function inside GameParent component has two state properties called AI and Game which are objects. I pass these objects down as a prop to the board component. It also has a function called startGame()

startGame() {
  let newAI = new AI(this.state.AIIdentity);
  let newGame = new Game(newAI,this.state.AIIdentity);
  this.state.AI.plays(this.state.Game);
  this.state.Game.start();
  this.setState({
    start: true,
    AI: newAI,
    Game: newGame,
  });
console.log("THIS!!!",this)
console.log("THIS!!!",this.state)
console.log("THIS!!!",this)
console.log("THIS!!!",this.state.Game);
}

When this.state.Game.start() is called there is a property called status inside the Game object that should be changed to "running"

I pass the startGame() function down to my gameControls component and I attach it to my start button onClick handler.

My board component handles the clicks on the squares of the board but it only registers clicks if the Game.status === "running" but I keep getting the object with a status === "beginning".

So when I added these 4 console.logs, when I print out only this, I see that the Game object's status is "beginning" however when I console.log this.state and this.state.Game, the status is set to "running"!

I am so confused why this is happening... I'm guess it's the way React update it's child but I haven't found an explanation from reading how render() and setState() works. Or maybe I'm not completely understanding how "this" is affect when I pass down functions and objects to child components.

If you guys want to see the full code, here is the link http://codepen.io/comc49/pen/WRqBXr?editors=0110

1
This could potentially be the same problem as stackoverflow.com/q/23392111/218196 .Felix Kling

1 Answers

0
votes
  1. You should not put function inside the state. State is for data only. I think that could be one source for unexpected behavior.

  2. this.setState is an asynchronous function, that means that there is no guarantee that the state is set right after you call this.setState. That could explain the unexpected output from the console.logs