我正在尝试更新嵌套状态对象的单个属性,并将其返回给状态。我有需要更新的对象的索引,但我正在努力更改一个属性并将新对象添加回状态。
我的状态对象看起来像这样,我正在尝试减少一个按下按钮的玩家的生命。
我一直在尝试使用数组过滤器,试图复制对象并将其添加回状态,但这会丢失对象的位置。
this.state = {
players: {
{id: 1, lives: 3, name: something},
{id: 2, lives: 3, name: something}
}
}
public removeLife(id): void {
const player = this.state.players[id];
player.lives = player.lives - 1;
this.setState({players[id]: {...player}
})
}
任何帮助都将不胜感激。
发布于 2019-08-12 21:33:22
在做了一些研究之后,我发现更新嵌套状态中的单个对象的最好方法是浅层复制状态,更改对象,然后将允许的状态对象重新分配回状态。如下所示:
public removeLife(event, id): void {
const newState = Object.assign([], this.state.players);
const indexOfPlayer = newState.findIndex(selectedPlayer => selectedPlayer.id === id);
const player = newState[indexOfPlayer];
player.lives = player.lives - 1;
this.setState({players: newState})
}
发布于 2019-08-08 02:47:50
因为你的state
包含一个对象的对象,所以我建议你把它变成一个对象的数组:
this.state = {
players: [
{id: 1, lives: 3, name: something},
{id: 2, lives: 3, name: something}
]
}
您需要像这样处理更新(例如,更新索引1中的播放器):
this.setState({
players: {...this.state.players,
players[1]: {...this.state.players[1], lives: this.state.players[1].lives + 1 }
}
})
或者尝试一下(我遵循你的函数):
public removeLife(id): void {
const player = this.state.players[id];
player.lives = player.lives - 1;
this.setState({players: {
...this.state.players,
players[id]: {...player}
}
})
}
https://stackoverflow.com/questions/57400524
复制相似问题