我怎样才能在使用 Context API 做出反应的购物车中没有重复值?

How can I not have duplicate value in shopping cart made with react using Context API?

这是我在 reducer 中用来将商品添加到购物车的代码,下面的 return 语句是我试图用来不允许购物车中出现任何重复商品而仅更改物品的数量。但它仍然没有用。数量确实更新了,但我仍然得到重复的值。所以请帮我解决这个问题,Thx

export const initialState = {
    cart: []
}

const Reducer = (state = initialState, action) =>{
    switch(action.type){
        case "ADD_TO_CART":
            const {id, quantity} = action.item
            let alreadyInCart = false, newQty=0
            
            state.cart.forEach(x =>{
                if(x.id === id){
                    alreadyInCart = true
                    newQty = parseInt(x.quantity+quantity)
                }
            })

            //let categories = [...new Set(Inventory.map(x=>x.category))]

            if(!alreadyInCart){
                return {
                    ...state,
                    cart: [...state.cart, action.item]
                }
            } else{
           ***return {
                  ...state,
                   cart: [...state.cart, 
                       {...action.item, quantity: newQty}
                   ]
               }***
            }
        default:
            return state
    }
}

export default Reducer

看来您只需要更新购物车中的现有商品,或将其添加到购物车。

试试这个。

export const initialState = {
  cart: [],
};

const Reducer = (state = initialState, action) => {
  switch (action.type) {
    case 'ADD_TO_CART':
      const nextCart = [...state.cart];
      const existingIndex = nextCart.findIndex((item) => item.id === action.item.id);

      if (existingIndex >= 0) {
        const newQuantity = parseInt(nextCart[existingIndex].quantity + action.item.quantity);

        nextCart[existingIndex] = {
          ...action.item,
          quantity: newQuantity,
        };
      } else {
        nextCart.push(action.item);
      }

      return {
        ...state,
        cart: nextCart,
      };
    default:
      return state;
  }
};

export default Reducer;