简体   繁体   English

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

[英]How add new field into reducer using Immer.js?

For example,例如,

state = {
  data: {}
}

How can I add a new nested field into an object?如何将新的嵌套字段添加到 object 中? I cannot set that field, because have an error Cannot read property 'date' of undefined我无法设置该字段,因为出现错误Cannot read property 'date' of undefined

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

As a result I want:结果我想要:

  data: {
     children: {
        data: 'date'
     }
  }
}

Normal JS object manipulation rules apply here.此处适用普通 JS object 操作规则。 You can't write obj.xyz = if there is no .y field yet - you have to create that first.如果还没有.y字段,您不能编写obj.xyz = - 您必须先创建它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM