我想使用spread运算符。场景是没有玩家(在UI上显示为玩家牌)。每当我点击任何播放器磁贴时,它就会变为活动状态(突出显示)。条件是一次只能突出显示一个玩家。因此,当点击播放器图块时,其属性为ifActive: true
,其余玩家属性为ifActive: false
playerReducer
点击播放器ID为action.payload
(action.payload
正在提供当前点击的播放器的ID)。现在我必须修改我的state
而不改变它。我必须使用spread运算符。如何使用扩展运算符修改索引处的特定对象?
const initialPlayerState = {
tabs: [
{ id: 1, name: 'player 1', ifActive: false },
{ id: 2, name: 'player 2', ifActive: false },
{ id: 3, name: 'player 3', ifActive: false },
]
}
const playerReducer = (state = initialPlayerState , action) => {
switch (action.type) {
case SELECT_PLAYER:
//how to modify state using spread operator, and how to modify
//a specific object at a specific index.
return { ...state, /*some code hrere*/};
default:
return state;
}
}
如何使用spread运算符修改索引处的特定对象?严格来说,我必须使用spread运算符,每个玩家都应该有
ifActive
属性。
答案 0 :(得分:1)
如果您需要更新其中一个players
,例如ifActive
标志,并重新创建tabs
数组以触发标签组件的重新渲染,您可以这样做
const initialPlayerState = {
tabs: [
{ id: 1, name: 'player 1', ifActive: false },
{ id: 2, name: 'player 2', ifActive: false },
{ id: 3, name: 'player 3', ifActive: false },
]
}
const playerReducer = (state = initialPlayerState , action) => {
switch (action.type) {
case SELECT_PLAYER:
return {
...state, // If you have something else in your state
tabs: tabs.map(player => player.ifActive || player.id === action.id ? {
...player,
ifActive: player.id === action.id
} : player)
};
default:
return state;
}
}
答案 1 :(得分:0)
return { ...state, players: state.players.map(player => ({ ...player, selected: player.id === action.id })) };