2017-06-16 30 views
0

我是一個學習用React.js構建RPG遊戲的新手,我發現這部分很混亂。(React.js)爲什麼反應無法找到對象?

我試圖更新lifeonClicklife < damage,該objectplayer被丟棄。因此,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

+0

分配條件檢查,比如'

您是:{this.props.targets && this.props.targets [this.props.playerindex] && this.props.targets [this.props.playerindex]。名稱}

' –

+0

@ShubhamKhatri你能解釋一下這段代碼嗎?它也會停止錯誤按摩,但有時會跳過最後一名玩家(Spud)。 –

+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});} 

這個問題已經解決,但如果你喜歡,請給我這個項目的建議!

+0

後,你使用setState時檢查這個錯誤https://stackoverflow.com/questions/44492678/when-does-reacts-setstate-變化的國家/ 44493095#44493095 –

相關問題