gpt4 book ai didi

javascript - react Redux : How to add a property to an empty object in the reducer

转载 作者:行者123 更新时间:2023-12-02 22:00:41 24 4
gpt4 key购买 nike

const INITIAL_STATE = {
editedProduct: {},
};

reducer .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,
},
],
},
});

我收到一个错误:可能的未处理的 Promise 拒绝(id:0):类型错误:传播不可迭代实例的尝试无效

问题出在这一行

...state.editedProduct[typeSwatch],

指的是尚未初始化的属性。

我该如何解决这个问题?

最佳答案

正如错误所示,您无法传播 null/undefined 值。这里最简单的方法是在尚未设置属性的情况下使用默认值,例如

...(state.editedProduct[typeSwatch] || [])

由于您在几个地方使用此值,因此进一步创建一个变量是有意义的。

关于javascript - react Redux : How to add a property to an empty object in the reducer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59888318/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com