我在这个项目中使用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是只读的。我如何更新"unit“变量,使它在应该递增的时候递增。
发布于 2021-07-10 19:57:23
在React Toolkit的createSlice中,您可以直接修改state,甚至应该这样做。所以不要创建副本,只需修改它即可。实际上,这个错误可能在某种程度上源于使用current进行复制。
See the "Writing Reducers with Immer" documentation page on this
同时,还有一个建议:
const CartListSlice = createSlice({
name: 'cartItem',
initialState,
reducers: {
addToCart: (state, action) => {
const existingItem = state.find(item => item.cartItem._id === action.payload._id)
if (existingItem) {
item.unit += 1
} else {
state.push({
cartItem: action.payload,
unit: 1
});
}
},
}
});发布于 2021-07-11 01:17:38
你不需要行:
let copyState = current(state.cartItem).slice();只需使用state.cartItem.map,而不是copyState
正如@phry所说,你应该直接突变state,因为redux-toolkit在后台使用immerJS来处理突变。
https://stackoverflow.com/questions/68326030
复制相似问题