防止 redux 将重复的项目添加到购物车

Prevent redux from adding duplicate items to cart

我正在使用 redux 将产品放入 react native 项目的购物车中。目前它可以正常工作,但我可以添加重复项。我想阻止这种情况。

修改将停止存储重复项的减速器的最佳方法是什么?

我的减速器:

const cartItems = (state = [], action) => {
  //action type are the constatns
  switch (action.type) {
    case ADD_TO_CART:
      // TODO: dont add duplicates
      return [...state, action.payload];
      
    case REMOVE_TO_CART:
      //filter through the single item that matches payload and remove it
      return state.filter(cartItem => cartItem !== action.payload);
    case CLEAR_TO_CART:
      //return empty state which clears cart
      return (state = []);
  }
  //return the state
  return state;
};

我的操作:

export const addToCart = (payload) => {
    return {
        type: ADD_TO_CART,
        payload,
    }
}

使用 find 检查状态中是否存在具有该产品 ID 的对象。如果它 return 状态,否则 return 更新状态。

const { product_id } = action.payload;
const dupe = state.find(obj => obj.product_id === product_id);
return dupe ? state : [...state, action.payload ];

您可以在执行以下操作之前添加一些代码:

return {...state, cart: [...state.cart].push(payload)}

。例如:

const lookForCart = state?.cart?.find(crt => crt?.cardId === payload?.cardId)
if (lookForCart) return state
return {...state, cart: [...state.cart].push(payload)}

您应该过滤掉商店中的产品并添加新的 action.payload

  • 这将确保负载 quantitypricetotalquantity 得到更新

代码:

case ADD_TO_CART:
  // TODO: dont add duplicates
  return [...state.filter(p => p.id !== action.payload.product_id), action.payload];
  

调用操作前必须先检查重复项add_cart

情况 1:如果不存在 => 推入数组 redux 存储

案例 2:如果有项目 => 考虑更改 属性 示例增加数量产品