如何使用Immer.js向reducer添加新字段?

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

例如,

state = {
  data: {}
}

如何将新的嵌套字段添加到对象中? 我无法设置该字段,因为有错误

Cannot read property 'date' of undefined

const reducer = produce((draft, action) => {
   switch (action.type) {
      case 'ACTION_SUCCESS':
      draft.data.children.date = action.response;
   }
});

结果我想要:

  data: {
     children: {
        data: 'date'
     }
  }
}
javascript redux reducers immer.js optional-chaining
2个回答
1
投票

这里适用普通的 JS 对象操作规则。如果还没有

obj.x.y.z =
字段,则无法写入
.y
- 您必须先创建该字段。


0
投票

你尝试过lodash/set吗?

import set from "lodash/set"

const obj= set({}, "path.to.nested.field", value)
© www.soinside.com 2019 - 2024. All rights reserved.