在这里,我调用了一个函数 addItem,在其中我增加了购物车的value
<CartItem
key={`cartItem-${item.item_id}`}
onIncrement={() => addItem(item)}
onDecrement={() => removeItem(item)}
onRemove={() => removeItemFromCart(item)}
data={item}
/>
我的上下文是
const addItemHandler = (item, quantity = 1) => {
dispatch({ type: 'ADD_ITEM', payload: { ...item, quantity } });
};
和我的 reducer 用于在 reducer.js 中添加项目
export const addItemToCart = (state, action) => {
const existingCartItemIndex = state.items.findIndex(
(item) => item.item_id === action.payload.item_id
);
if (existingCartItemIndex > -1) {
const newState = [...state.items];
newState[existingCartItemIndex].quantity += action.payload.quantity;
return newState;
}
return [...state.items, action.payload];
};
const reducer = (state, action) => {
switch (action.type) {
case 'ADD_ITEM':
return { ...state, items: addItemToCart(state, action) };
default:
throw new Error(`Unknown action: ${action.type}`);
}
};
此代码将计数器增加 2 而不是增加 1。