5

我想使用传播运算符。场景是没有玩家(在 UI 上显示为玩家图块)。每当我单击任何播放器图块时,它都会变得活跃(突出显示)。条件是一次只能突出显示一名玩家。所以,当一个玩家瓷砖被点击它的属性ifActive: true时,其余的玩家属性ifActive: falseplayerReducer点击的玩家id为action.payloadaction.payload给出当前点击的玩家的id)。现在我必须修改我的state而不改变它。我必须为此使用扩展运算符。如何使用扩展运算符修改索引处的特定对象?

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

如何使用扩展运算符修改索引处的特定对象?严格来说,我必须使用扩展运算符,每个玩家都应该有ifActive属性。

4

2 回答 2

2

如果您需要更新其中一个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;
        }
    }
于 2016-09-05T07:35:00.847 回答
2
return { ...state, players: state.players.map(player => ({ ...player, selected: player.id === action.id })) };
于 2016-09-14T05:36:48.217 回答