如何在 react-redux 中使用扩展运算符修改索引处的特定对象?

how to modify a specific object at a index using spread operator in react-redux?

我想使用展开运算符。场景是没有玩家(在 UI 上显示为玩家图块)。每当我点击任何播放器瓷砖时,它就会变得活跃(突出显示)。条件是一次只能突出显示一名玩家。所以,当一个玩家板块被点击时,它的属性 ifActive: true,其他玩家的属性 ifActive: false playerReducer 被点击的玩家 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;
    }
}

how to modify a specific object at a index using spread operator? Strictly, I have to use spread operator and each player should have ifActive attribute.

如果您需要更新 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;
        }
    }
return { ...state, players: state.players.map(player => ({ ...player, selected: player.id === action.id })) };