[英]Limiting the number of same-product items to 1 in a shopping cart with React JS
我目前正在做我的第一個項目,這是一家二手服裝和配飾店。 目前,每次我單擊“添加到購物車”按鈕時,它都會添加產品,這很棒,但考慮到它應該是每個產品的一個項目,我想要它,所以一旦你將它添加到購物車,產品不可用於第二次添加。
我的代碼如下所示:
產品卡:
export default function ProductCard(props) {
const context = React.useContext(Context);
const addToCart = () => {
context.dispatch({
code: "ADD-PRODUCT-TO-CART",
payload: props.product,
});
};
和上下文:
const reducer = (state, action) => {
console.log(state, action);
switch (
action.code )
從技術上講,這就是魔法應該發生的地方:
{
case "ADD-PRODUCT-TO-CART":
if (state.cart.name === state.cart.name) {
alert("The maximum quantity for this product is 1");
console.log("disable button");
}
return { ...state, cart: [...state.cart, action.payload] };
case "REMOVE-FROM-CART":
console.log(action);
return {
...state,
cart: state.cart.filter((product, index) => {
if (action.payload !== index) {
return true;
} else {
return false;
}
}),
};
default:
return state;
}
};
const Context = React.createContext();
const Provider = (props) => {
const [state, dispatch] = React.useReducer(reducer, initialState);
return (
<Context.Provider value={{ state, dispatch }}>
{props.children}
</Context.Provider>
);
};
export { Context, Provider, reducer };
任何建議都會有所幫助!
謝謝!
根據檢查產品 ID 是否已存在於購物車中,應在產品卡組件中禁用添加到卡按鈕。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.