我正在尝试增加对象的减速器函数内的计数。在“addItem”操作中,如果添加的商品已存在于商店中,我会尝试增加计数。
import { createSlice, current } from "@reduxjs/toolkit";
import React from "react";
const cartSlice = createSlice({
name: "cart",
initialState: {
items: [],
},
reducers: {
**addItem:** (state, action) => {
let a = 0;
current(state.items).map((item) => {
console.log(item, "hey there");
if (item === action.payload) {
console.log("Matched");
console.log("Count1 is", ++item.card.info.count);
item.card.info.count = item.card.info.count + 1;
console.log("Count2 is", item.card.info.count);
a = 1;
return;
}
});
if (a == 0) {
state.items.push(action.payload);
}
**}**,
removeItem: (state, action) => {
state.items.pop();
},
clearCart: (state, action) => {
state.items.length = 0;
},
},
});
export const { addItem, removeItem, clearCart } = cartSlice.actions;
export default cartSlice.reducer;
我在下面附上控制台输出。
{card: {…}} 'hey there'
cartSlice.js:15 Matched
cartSlice.js:16 Count1 is 1
cartSlice.js:18 Count2 is 0
cartSlice.js:13 {card: {…}} 'hey there'
cartSlice.js:15 Matched
cartSlice.js:16 Count1 is 1
cartSlice.js:18 Count2 is 0
cartSlice.js:13 {card: {…}} 'hey there'
cartSlice.js:15 Matched
cartSlice.js:16 Count1 is 1
cartSlice.js:18 Count2 is 0
cartSlice.js:13 {card: {…}} 'hey there'
cartSlice.js:15 Matched
cartSlice.js:16 Count1 is 1
cartSlice.js:18 Count2 is 0
cartSlice.js:13 {card: {…}} 'hey there'
cartSlice.js:15 Matched
cartSlice.js:16 Count1 is 1
cartSlice.js:18 Count2 is 0
给我一些关于我在这里做错了什么的建议。预先感谢。
一般来说,改变减速器中的嵌套状态并不是一个好的做法。您应该创建副本。减速器不应该有副作用:https://redux.js.org/usage/side-effects-approachesRedux Toolkit 的 createSlice 在幕后为您处理不变性,但仅限于状态对象的顶级属性。
要解决此问题,在 addItem 中您可以执行以下操作:
addItem: (state, action) => {
const existingItem = state.items.find(item => item.card === action.payload.card);
if (existingItem) {
// If the item already exists, create a new array with updated counts
state.items = state.items.map(item => {
if (item.card === action.payload.card) {
return {
...item,
card: {
...item.card,
info: {
...item.card.info,
count: item.card.info.count + 1
}
}
};
}
return item;
});
} else {
// If the item doesn't exist, create a new array with the added item
state.items = [...state.items, action.payload];
}
}