【问题标题】:React Redux, Update part of state with immutability-helper updateReact Redux,使用 immutability-helper update 更新部分状态
【发布时间】:2019-02-05 06:46:59
【问题描述】:

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

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

我只想更新对象中的 items1 or 2 或任何其他键,其余状态保持不变。该操作包含键号为action.idaction.payload 包含字符串。

我对@9​​87654326@ 和update 的工作原理以及如何保持users 的其余部分保持不变感到困惑。

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

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

【问题讨论】:

    标签: reactjs redux react-redux immutability reducers


    【解决方案1】:

    这正是update 的用法,它将保持状态的其余部分不变。所以没有必要传播

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

    【讨论】:

      【解决方案2】:

      您可以像这样使用其余扩展运算符仅更新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
            }
          }
        };
      

      【讨论】:

      • 嗨,Amir,使用 rest spread 运算符,您不需要 immutability helper
      • 这里的用户:{我无法读取未定义的属性'1'
      • 您确定状态中的users 对象中已经存在1 键吗?
      • 你能在返回这个更新之前在这里打印出你的状态对象吗?
      • 我在帖子中写的是我在商店状态中看到的内容,用户是现在唯一的对象是状态,里面有键控对象。(只是添加了一对{})跨度>
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      • 2019-05-30
      • 1970-01-01
      • 1970-01-01
      • 2018-12-12
      • 2018-12-17
      相关资源
      最近更新 更多