[英]React Redux: How to add a property to an empty object in the reducer
const INITIAL_STATE = {
editedProduct: {},
};
reducer.js减速器.js
case ADD_SWATCH:
const typeSwatch = action.payload;
return merge(state, {
editedProduct: {
...state.editedProduct,
[typeSwatch]: [
...state.editedProduct[typeSwatch],
{
dimSwtNo: state.editedProduct[typeSwatch].length
? state.editedProduct[typeSwatch].length + 1
: 1,
},
],
},
});
I get an error: Possible Unhandled Promise Rejection (id: 0): TypeError: Invalid attempt to spread non-iterable instance我收到一个错误:可能未处理的承诺拒绝(ID:0):类型错误:传播不可迭代实例的尝试无效
The problem is in this line问题出在这一行
...state.editedProduct[typeSwatch],
Refers to a property that has not yet been initialized.指尚未初始化的属性。
How could I solve this problem?我怎么能解决这个问题?
As the error suggests, you can't spread a null
/ undefined
value.正如错误所暗示的那样,您不能传播
null
/ undefined
值。 The simplest approach here is to use a default value in scenarios where the property has not been set yet eg这里最简单的方法是在尚未设置属性的情况下使用默认值,例如
...(state.editedProduct[typeSwatch] || [])
Since you use this value in a couple of places it would make sense to create a variable further up.由于您在几个地方使用此值,因此进一步创建一个变量是有意义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.