【发布时间】:2021-07-10 08:21:28
【问题描述】:
我在这个项目中使用 react-redux 和 redux-toolkit。我想将商品添加到购物车。如果购物车中已经有相同的商品,只需增加单位。错误发生在切片上,所以这里只显示切片。
const CartListSlice = createSlice({
name: 'cartItem',
initialState,
reducers: {
addToCart: (state, action) => {
let alreadyExist = false;
// get a copy of it to avoid mutating the state
let copyState = current(state.cartItem).slice();
// loop throught the cart to check if that item is already exist in the cart
copyState.map(item => {
if (item.cartItem._id === action.payload._id) {
alreadyExist = true;
item.unit += 1 // <--- Error occurs here
}
})
// If the item is not exist in the cart, put it in the cart and along with its unit
if (alreadyExist === false) {
state.cartItem.push({
cartItem: action.payload,
unit: 1
});
}
},
}
});
我收到一个类型错误,告诉我unit 是只读的。
我怎样才能更新“单位”变量,以便它在它应该增加的时候增加。
【问题讨论】:
-
你能告诉我们
initialState吗?另外,你能给我们一个codesandbox上的代码示例吗? -
哦,当然,
const initialState = { cartItem: [], } -
您是否尝试过摆脱
copyState并在您的addToCart减速器函数中使用state.cartItem? -
没有
current。只需删除current,其余的留下,让我们知道它是否有效 -
哦,谢谢,删除 copyState 后,它可以工作了。非常感谢您帮助我。