这里我调用了一个函数 addItem,其中我增加了购物车的价值
<CartItem
key={`cartItem-${item.item_id}`}
onIncrement={() => addItem(item)}
onDecrement={() => removeItem(item)}
onRemove={() => removeItemFromCart(item)}
data={item}
/>
Run Code Online (Sandbox Code Playgroud)
我的背景是
const addItemHandler = (item, quantity = 1) => {
dispatch({ type: 'ADD_ITEM', payload: { ...item, quantity } });
};
Run Code Online (Sandbox Code Playgroud)
和我的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) => { …Run Code Online (Sandbox Code Playgroud)