(React.js)为什么React无法找到对象?
我是一个新手,正在学习使用React.js构建rpg游戏,但我发现这一部分非常令人困惑.
I am a newbie learning to build a rpg game with React.js, and I found this part very confusing.
我试图用onClick
更新life
,并且当life
< damage
时,object
player
被删除.因此html看起来像这样:
I am trying to update life
with onClick
and when life
<damage
, the object
player
is dropped. So the html looks like this:
当前播放器的生成方式如下:
The current player is generated like this:
<h4>You are: {this.props.targets[this.props.playerindex].name}</h4>
我使用这些代码来处理攻击并更新索引:
I use these code to handle attack and update the index:
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();
}
但是有时索引会增加,而索引却不会增加,并导致以下情况:
But sometimes the index will increment while it should not, and causes this:
我认为这可能是setState
的异步行为,但是我不知道该如何解决这个问题.
I think it might be the asynchronous behavior of setState
, but I don't know how should I solve this problem.
如果您有解决方案或其他方法来实现预期的行为,请提供帮助!
If you have a solution or another way to achieve the expected behavior, please help!
此处的代码:
App.js
: https://ghostbin.com/paste/e9wjg
Attack.js
: https://ghostbin.com/paste/3zbwk
我知道我做错了:
当我放下一个对象时,我应该将索引移回去:
when I am dropping a object, I should move the index back:
if (life>damage){
players[index2].life = life-damage;}
else {players=players.filter(player => player.id !== id2);
this.setState({playerindex:this.state.playerindex-1});}
此问题已解决,但是如果您愿意,请给我有关该项目的建议!
This problem is solved, however please give me advice on this project if you like!