【问题标题】:Why is my console.log showing different property values if I'm using the same object?? reactjs如果我使用同一个对象,为什么我的 console.log 会显示不同的属性值?反应
【发布时间】:2017-03-08 04:15:01
【问题描述】:

您好,情况是这样的。我正在用 react 构建一个 tictactoe 游戏,我有 3 个组件 1. 游戏家长 2. 董事会 3. 游戏控制

我在 GameParent 组件中有一个函数,它有两个状态属性,称为 AI 和 Game,它们是对象。我将这些对象作为道具传递给板组件。它还有一个叫做 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);
}

当 this.state.Game.start() 被调用时,Game 对象内部有一个名为 status 的属性,应将其更改为“正在运行”

我将 startGame() 函数传递给我的 gameControls 组件,并将它附加到我的开始按钮 onClick 处理程序。

我的棋盘组件处理棋盘方块上的点击,但它仅在 Game.status ===“正在运行”时注册点击,但我不断获取状态 ===“开始”的对象。

所以当我添加这 4 个 console.logs 时,当我只打印出这个时,我看到 Game 对象的状态是“开始”但是当我 console.log this.state 和 this.state.Game 时,状态是设置为“运行”!

我很困惑为什么会发生这种情况......我猜这是 React 更新它的孩子的方式,但我还没有通过阅读 render() 和 setState() 的工作原理找到解释。或者当我将函数和对象传递给子组件时,我可能没有完全理解“this”的影响。

如果你们想看完整的代码,这里是链接 http://codepen.io/comc49/pen/WRqBXr?editors=0110

【问题讨论】:

标签: javascript reactjs this reactive-programming


【解决方案1】:
  1. 你不应该把函数放在状态中。状态仅用于数据。我认为这可能是意外行为的来源之一。

  2. this.setState 是一个异步函数,这意味着不能保证在您调用this.setState 后立即设置状态。这可以解释来自 console.logs

  3. 的意外输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    • 2014-02-13
    • 2012-04-16
    相关资源
    最近更新 更多