How to change a specific object by index using the spread operator in a reduction reaction?

I want to use the spread operator. The scenario is that there are no players (displayed as a player player in the user interface). Whenever I click on a player of a player, he becomes active (highlighted). The condition is that only one player should be singled out at that time. So, when the player of the player clicks his attribute ifActive: true, and the attribute of the other players ifActive: false playerReducerreceives the click of the player-id as action.payload( action.payloadindicates the identifier of the player who is currently pressed). Now I have to change my statewithout changing it. I have to use the distribution operator for this. How to change a specific object by index using the spread operator?

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
return { ...state, players: state.players.map(player => ({ ...player, selected: player.id === action.id })) };
0

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

Source: https://habr.com/ru/post/1653643/


All Articles