[英]React Native updating single property of nested object in state
我試圖更新嵌套狀態對象的單個屬性並將其返回到狀態。 我有我需要更新的對象的索引,但我正在努力改變一個屬性並將新對象添加回狀態。
我的狀態對象看起來像這樣,我試圖通過按鈕按下來減少玩家的生命。
我一直在使用數組過濾器,嘗試復制對象並將其添加回狀態,但這會丟失對象位置。
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}
})
}
任何幫助將不勝感激。
在做了一些研究后,我發現在嵌套狀態下更新單個對象的最佳方法是淺復制狀態,更改對象然后將淺狀態對象重新分配回狀態。 像這樣:
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})
}
因為你的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}
}
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.