我在 redux reducer 中有一个案例,我使用了一个 object.assign 来获取我的状态的副本,我想将其转换为新的语法扩展运算符“...state”,我该如何制作它,
无需进行突变!
case INCREASE_QUANTITY: {
return Object.assign({}, state, {
cart: state.cart.map(item => {
if (item.product.id === action.productInfo.product.id) {
return Object.assign({}, item, {
quantity: action.quantity + 1,
});
}
return item;
}),
});
}
最佳答案
您打开一个对象文字,从 ...state
开始,将其扩展到新对象中,然后使用 cart
属性(以及相同的概念)对于内部):
case INCREASE_QUANTITY: {
return {
...state,
cart: state.cart.map(item => {
if (item.product.id === action.productInfo.product.id) {
return {
...item,
quantity: action.quantity + 1,
};
}
return item;
}),
};
}
通过按该顺序执行此操作,您可以确保 cart
(或内部购物车的 quantity
)覆盖跨价中的属性。对象字面量中后面的属性“胜过”前面的属性。
关于javascript - 转换对象以使用扩展运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58363036/