更新嵌套数组中的对象,react-redux

时间:2019-05-24 11:21:59

标签: reactjs redux react-redux

我正在尝试更新嵌套数组中的对象,下面是我的状态示例。我正在尝试更新目标内的对象,我成功地更新了对象。

但是

每次我更新任何对象。索引为0的对象将获得所有对象的副本。更新的次数越多,它就会创建更多的副本,并且它们会嵌套在对象中的索引0处。

索引0处的对象也将使用任何对象的最新更新进行更新。

{
  list: {
    '0': {
      id: 0,
      dueDate: 'By May 28th I Will have: ',
      goals: [
        {
         0: {...}
         1: {...}
         3: {...}
        }
      ]
    }
   '1':{
      id: 0,
      dueDate: 'By June 31st I Will have: ',
      goals: [
        {
         2: {...}
         4: {...}
        }
}

keyName =列表中对象的索引。 (“ 0”和“ 1”上方的两个:  )

减速器

      return {
        ...state,
        [action.payload.keyName]: {
          ...state[action.payload.keyName],
          goals: [
            { ...state[action.payload.keyName].goals, ...action.payload.goal },
            ...state[action.payload.keyName].goals.slice(1, state[action.payload.keyName].goals.length)
          ]
        }
      };

此外,如果您知道有关normalizr的任何好的文档或教程,请告诉我。

先谢谢您! :)

2 个答案:

答案 0 :(得分:0)

假设目标具有唯一键,这将根据其键更新goal

const state = {  
    '0': {
      id: 0,
      dueDate: 'By May 28th I Will have: ',
      goals: [        
         {a: 1,
         b: 1,
         c: 1}
      ]
    },
   '1':{
      id: 0,
      dueDate: 'By June 31st I Will have: ',
      goals: [        
         {d: 1,
         r: 1}
      ]
   }
        
};

function reducer(state, keyName = 0, goal) {

 const goals = [...state[keyName].goals];
 const index = state[keyName].goals.findIndex((e) => Object.keys(e).every((key) => Object.keys(goal).includes(key)));
 goals.splice(index,1, goal);
 
 return {
  ...state,
  [keyName]: {
   ...state[keyName],
   goals, 
  }
 };
}

console.log(reducer(state, 0, {a:3, b:2, c:4}));

这是假设您要通过数组定位来更新目标。

const state = {  
    '0': {
      id: 0,
      dueDate: 'By May 28th I Will have: ',
      goals: [        
         {test: 1},
         {test: 1},
         {test: 1}        
      ]
    },
   '1':{
      id: 0,
      dueDate: 'By June 31st I Will have: ',
      goals: [        
         {test: 1},
         {test: 1}
      ]
   }
        
};

function reducer(state, keyName = 0, goal) {
 return {
  ...state,
  [keyName]: {
   ...state[keyName],
   goals: [{...state[keyName].goals, ...goal}]
  }
 };
}

console.log(reducer(state, 0, [{test:3}, {test:44}]));

答案 1 :(得分:0)

Johan好像您以错误的方式破坏了您的状态。 首先,尝试使用数组解构goals: [{...state[keyName].goals, ...newGoal}]更新目标 而且也许这可能有用https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns#updating-nested-objects