Reactjs:setState没有为状态赋值

时间:2017-10-13 07:53:05

标签: javascript reactjs

我需要帮助,你是唯一能给我的人:D 我正在学习反应,试图开发一个简单的格斗游戏。

我尝试更新一个状态(在下面一行)来定义轮到它的命令是:

this.setState({itsRou​​nd:rand},console.log(' test:' + this.state.whoseRound))

它不会更新我的状态。我的州的价值仍然是0.我不明白为什么,如果有人可以救我!

感谢所有人。



class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      characters: [], //contains Array of characters objects
      readyToFight: false, // character selected or not
      firstPlayerCharacter: null, //contains key of character on select
      secndPlayerCharacter: null, //contains key of character on select
      whoseRound: 0 // defines whose character attacks
    }
  }

  //Run the fight
  setFight = () => {
    let firstFighter = this.state.characters[this.state.firstPlayerCharacter]
    let secndFighter = this.state.characters[this.state.secndPlayerCharacter]

    this.initiateFight(firstFighter, secndFighter);
  }

  //initiate fight rounds
  initiateFight = (firstFighter, secndFighter) => {

    // set who attacks first randomly => returns 1 or 2
    var rand = randomDice(1, 2)

    // !!!!! HERE: My console.log always display 0
    this.setState({whoseRound: rand}, console.log('test:' + this.state.whoseRound))

    while(firstFighter.stats.health > 0 || secndFighter.stats.healthh > 0){
      // depending on whoseRound is, we set an attacker and a defenser
      1 === this.state.whoseRound ? this.runRound(firstFighter, secndFighter) : this.runRound(secndFighter, firstFighter)
    }
  }

  // Lance les actions définies pour un round
  runRound = (attacker, defender) => {
    let hit = false
    let cc = false
    let damages

    hit = randomDice(0, 100) <= this.getHitChances(attacker, defender)
    cc = randomDice(0, 100) <= this.getCriticalChances(attacker, defender)
    damages = this.getDamages(attacker, defender, cc)

    if(hit)
    {
      //console.log(attacker.name + ' attaque ' + defender.name + ' et lui occtroie ' + damages + ' points de dégats')
      //console.log('les points de vie de ' + defender.name + ' passent de ' + defender.stats.health + ' à ' + (defender.stats.health - damages))
      defender.stats.health -= damages
    }

    //Now, it's the other character's turn
    1 === this.state.whoseRound ? this.setState({whoseRound: 2}) : this.setState({whoseRound: 1})

  }
  
}

export default App;
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

setState()中的第二个参数是回调。换句话说,它需要一个功能。因此,您必须将要执行的代码包装在函数中。

像这样:

// !!!!! HERE: My console.log always display 0
this.setState({whoseRound: rand}, function() {console.log('test:' + this.state.whoseRound)})

或者使用箭头功能,如果您愿意:

// !!!!! HERE: My console.log always display 0
this.setState({whoseRound: rand}, () => {console.log('test:' + this.state.whoseRound)})