(React.js)为什么反应无法找到对象?

时间:2017-06-16 14:50:28

标签: javascript reactjs frontend

我是一个学习使用React.js建立RPG游戏的新手,我发现这部分非常令人困惑。

我正在尝试使用life更新onClick,当life< damage时,object player将被删除。所以html看起来像这样:

enter image description here

当前播放器生成如下:

<h4>You are: {this.props.targets[this.props.playerindex].name}</h4>

我使用这些代码来处理攻击并更新索引:

handleAttack(index1,id2){
    let players = this.state.players.slice();
    let index2 = players.findIndex(x => x.id === id2);
    let damage = players[index1].damage;
    let life = players[index2].life;
    console.log("Before(length):"+this.state.players.length);
    if (life>damage){
        players[index2].life = life-damage;}
    else {players=players.filter(player => player.id !== id2);}
    this.setState({players},()=>{console.log("After(length):"+this.state.players.length);
                                 this.handleUpdateIndex();});
}

handleUpdateIndex(){
    console.log("Before:"+this.state.playerindex);
    let index=this.state.playerindex;
    let length=this.state.players.length;
    console.log("BeforeUpdate(length)"+this.state.players.length);
    if(index<length-1)
    {this.setState({playerindex:index+1},() => {console.log("After:"+this.state.playerindex);});}
    else{this.setState({playerindex:0},() => {console.log("After:"+this.state.playerindex);});}
    this.forceUpdate();
}

但有时索引会增加而不应该增加,并导致:

enter image description here

我认为这可能是setState的异步行为,但我不知道应该如何解决这个问题。

如果您有解决方案或其他方式来实现预期的行为,请提供帮助!

代码在这里:

App.jshttps://ghostbin.com/paste/e9wjg

Attack.jshttps://ghostbin.com/paste/3zbwk

1 个答案:

答案 0 :(得分:0)

我知道我错了:

当我放弃一个对象时,我应该将索引移回:

   if (life>damage){
        players[index2].life = life-damage;}
    else {players=players.filter(player => player.id !== id2);
          this.setState({playerindex:this.state.playerindex-1});}

这个问题已经解决了,但是如果你愿意,请给我这个项目的建议!