简体   繁体   English

Redux Reducer - 如何在不改变状态的情况下更新对象值?

[英]Redux Reducer - How to update an object value without mutating the state?

My reducer looks like this: 我的减速机看起来像这样:

  const players = (state = {}, action) => {
    switch (action.type) {
      case 'UPDATE_PLAYERS_CARDS':
        return Object.assign({}, state, {
          [action.player]: {
            name: state[action.player].name,
            score: state[action.player].score,
            cards: action.cards
          }
        })
       default:
         return state
    }
  }

  export default players

Basically, I just want to update the players cards but if I don't include the name and the score, then those get deleted in the new state. 基本上,我只想更新球员卡,但如果我不包括名称和分数,那么这些将在新状态下被删除。

Ideally I need to just do something like this: state[action.player].cards = action.cards but one of the rules is to never mutate the state . 理想情况下,我需要做这样的事情: state[action.player].cards = action.cards但其中一条规则是永远不要改变状态

The method above will work, but that requires me to always know the data structure so if I add something else to it in the future, I would need to remember to come back to this reducer and add that back in so I don't lose it. 上面的方法可行,但这需要我总是知道数据结构,所以如果我将来添加其他东西,我需要记得回到这个reducer并重新添加,所以我不会丢失它。

Is there a better way to accomplish this? 有没有更好的方法来实现这一目标?

Edit: Thanks to Vijay for the suggestion for multiple object assigns. 编辑:感谢Vijay提出多个对象分配的建议。 I ended up getting it to work with this: 我最终得到了这个:

case 'UPDATE_PLAYERS_CARDS':
  const playerObject = Object.assign(state[action.player], { cards: action.cards });
  return Object.assign({}, state, {
    [action.player]: playerObject
  });

How is that? 那个怎么样? Let me know if there are any improvements I can make. 如果我能做出任何改进,请告诉我。

Multiple Object.assign methods look ugly. 多个Object.assign方法看起来很丑陋。

You can do: 你可以做:

return { ...state.action.player, cards: action.cards }

Note: You'll need stage-2 babel preset to use this. 注意:您需要使用stage-2 babel预设来使用它。

Once the data structure to update becomes fairly complex, you can use ImmutableJS 's setIn , updateIn methods to do deep updates easily. 一旦要更新的数据结构变得相当复杂,您可以使用ImmutableJSsetInupdateIn方法轻松进行深度更新

Multiple Object.assign might help: 多个Object.assign可能会有所帮助:

const newState = Object.assign({}, state);
Object.assign(newState.action.player, { cards: action.cards });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM