【问题标题】:how to modify a specific object at a index using spread operator in react-redux?如何在 react-redux 中使用扩展运算符修改索引处的特定对象?
【发布时间】:2017-01-12 11:56:08
【问题描述】:

我想使用扩展运算符。场景是没有玩家(在 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;
    }
}

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

【问题讨论】:

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


    【解决方案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;
            }
        }
    

    【讨论】:

    • 这是错误的,因为您正在使用 splice 改变 tabs,而 tabs 是需要不可变的旧状态的一部分。你应该使用slice,而不是splice
    • 这也是错误的,因为您未能取消设置以前的ifActive
    • splice 很好,我的错,谢谢。你对 ifActive 标志的错误更新是正确的。
    • @DDS 好吧,因为我对 React-Redux 很陌生,所以我不太清楚你的意思。您能否详细告诉我需要做什么。这将是很大的帮助。
    【解决方案2】:
    return { ...state, players: state.players.map(player => ({ ...player, selected: player.id === action.id })) };
    

    【讨论】:

      猜你喜欢
      • 2023-01-12
      • 2020-04-06
      • 1970-01-01
      • 1970-01-01
      • 2017-06-28
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      • 2021-04-08
      相关资源
      最近更新 更多