React Redux,使用immutability-helper update更新状态的一部分

问题描述 投票:0回答:2

在我的redux reducer状态中,我想更新对象对象内的属性。

    {
    users:{
        '1':{id:'1', name:'', items:[], ....}
        '2':{id:'1', name:'', items:[], ....}
         ...
         }
    }

我想更新对象items在对象中使用键1 or 2或任何其他键和其他状态未触及。该操作包含键号为action.idaction.payload包含String。

我很困惑spreadupdate如何工作以及如何保持其余的users物体不受影响。

当然我的代码是错的:)但我试过了

case types.UPDATE_ITEMS: {
      return update(...state, {
        [action.id]: { items: { $set: action.payload } }
      });
    }
reactjs redux react-redux immutability reducers
2个回答
0
投票

这正是update的用法,它将保持国家的其余部分不受影响。所以没有必要传播

   case types.UPDATE_ITEMS:
          return update(state, {
            [action.id]: {
              items: { $set: action.payload }
            }
          });

-1
投票

你可以使用其余的扩展运算符更新users部分,如下所示:

case types.UPDATE_ITEMS:
  return {
    ...state, // That will keep any other keys in the object besides 'users'
    users: {
      ...state.users, // keep the part you want to keep from 'users',
      [action.id]: {
        ...state.users[action.id], // keep the part you want from this user
        items: [action.payload] // update the part you want
      }
    }
  };
© www.soinside.com 2019 - 2024. All rights reserved.