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

时间:2016-09-05 06:38:57

标签: javascript reactjs redux react-redux spread-syntax

我想使用spread运算符。场景是没有玩家(在UI上显示为玩家牌)。每当我点击任何播放器磁贴时,它就会变为活动状态(突出显示)。条件是一次只能突出显示一个玩家。因此,当点击播放器图块时,其属性为ifActive: true,其余玩家属性为ifActive: false playerReducer点击播放器ID为action.payloadaction.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属性。

2 个答案:

答案 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 })) };