【问题标题】:How to update nested object in redux如何在 redux 中更新嵌套对象
【发布时间】:2019-05-23 10:58:41
【问题描述】:

我有一个对象:

{ //birthdaysObject
    '2000':{
        'January':
         [{
             name: 'Jerry'
         },
         {
             name: 'Chris'
         }]
    },
    '2001':{
        'February':
         [{
             name: 'John'
         }]
    }

当我去更新 redux 存储时,它会将整个年份(例如“2000”)对象替换为我发送到减速器的新对象。

如何在不替换整个年份对象的情况下推送嵌套的对象数组?

我的减速器目前看起来像:

    return Object.assign({}, state, {
        ...state,
        birthdays: Object.assign({}, state.birthdays, {
            ...state.birthdays,
            ...birthdays
        })
    });

其中...birthdays 将是与第一个代码 sn-p 格式相同的另一个对象。

我也愿意接受有关我的数据结构、规范化等方面的建议。

任何帮助将不胜感激。

birthdaysObject 中的对象键是未知的,并且是在迭代一个单独的对象时分配的。我试过kolodny/immutability-helper 但是$merge 函数返回的结果与我的reducer 已经在做的结果相同。

【问题讨论】:

  • @imjared 感谢您将我指向该线程。从现在开始,我可能会将该助手用于我的减速器功能,但是对于这个特殊问题,它给我的结果与我编写的减速器相同。

标签: reactjs redux


【解决方案1】:

前段时间我也遇到过同样的问题。 按照我的做法。 你有一个对象,但我认为你应该有一个对象数组。 我对变量也有不同的名称,但这应该不是理解逻辑的问题

        //do a copy of the array first
        let newSubscriptions = state.customer.master.subscriptions.slice();
        
        //for the value you want to change, find it's position in the array first
        const indexInSubscriptions =  newSubscriptions.map(function(item) {
          return item.id;
        }).indexOf( action.id);
        
        //get the child you want to edit and keep it in a new variable
        const under_edit_subscription = state.customer.master.subscriptions[indexInSubscriptions];
        
        //go again over the array and where is the value at the index find above, replace the value
        newSubscriptions = newSubscriptions.map((item, i) => 
                    i === indexInSubscriptions ? under_edit_subscription : item
                   )

        //add the whole array into the state
        return {
          ...state,
          customer: {
            ...state.customer,
            master: {
            ...state.customer.master,
            subscriptions : newSubscriptions
            }
          }
        }

【讨论】:

  • 谢谢,我不一定会接受你的解决方案。但是,我确实创建了一个对象数组,它更容易使用。我最终用新的对象替换了整个生日对象。我本来希望能够将一个新项目推送到生日对象,但我认为我应该先研究规范化该数据结构,然后再做。感谢您的帮助!
猜你喜欢
  • 2018-06-03
  • 1970-01-01
  • 2018-07-04
  • 2019-10-10
  • 2019-02-26
  • 1970-01-01
  • 2020-10-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多