0

我想解释一下我的用例,这样你就可以很好地理解它

当用户将产品(product_id = 1)两次添加到购物车并且产品具有相同的选项(红色,xl)时,我有购物车和产品我增加了数量,

如果用户添加相同(product_id = 1)但有其他选项(绿色,xl),我将此产品作为单独的产品添加到购物车。

现在这很好用!

但是当用户在添加了上述2个产品后,再次添加具有相同选项(红色,xl)的相同产品时,它被添加为单独的产品!

如果之前存在的产品选项应该增加数量,否则我期望将其单独添加。

我试过的

将选项 id 添加到 Product 属性中并检查它之前是否存在然后处理我想要的但它不能很好地工作并将第三个产品添加为单独的产品!

屏幕记录

代码片段

zustand专卖店

interface CartProductsProp extends State {
  cartProducts: ProductProps[];
  addToCart: (Products: ProductProps) => void;
  updateProductQuantity: (
    Product: ProductProps,
    updatedQuantity: number,
  ) => void;
  checkProductOptionsExist: (
    Product: ProductProps,
    updatedQuantity: number,
  ) => void;
  ...
}


export const useCartProduct = create<CartProductsProp>(
  persist(
    (set, get) => ({
      cartProducts: [],
      addToCart: (product) => {
        set((prev) => ({
          cartProducts: [...prev.cartProducts, {...product}],
        }));
      },
      checkProductOptionsExist: (
         product: ProductProps,
         updatedQuantity: number,
       ) => {
         set((prev) => {
           console.log('->prev', JSON.stringify(prev.cartProducts));
           console.log(
          'check==>IDs',
              cartProduct.id === product.id &&
              product.productOptionIds === cartProduct.productOptionIds,
           ); // for some reason this run towic when add the third product"with same options as first product "red,xl" true then false

           return prev.cartProducts.map((cartProduct) => {
             cartProduct.id === product.id &&
             product.productOptionIds === cartProduct.productOptionIds
               ? get().updateProductQuantity(product, updatedQuantity)
               : get().addToCart(product);
           });
         });
       },
       // To Update the quantity when product exist in cart before
       updateProductQuantity: (
         product: ProductProps,
         updatedQuantity: number,
       ) => {
         set((prev) => {
           let currentCart = prev.cartProducts.map((cartProduct) =>
             cartProduct.id === product.id &&
             areEqual(cartProduct.selectedOptions, product.selectedOptions)
               ? 
                 {
                  ...product,
                  quantity: cartProduct?.quantity! + updatedQuantity,
                  updated: 'yes@',
                  productTotalPrice:
                    (cartProduct?.quantity! + updatedQuantity) *
                    cartProduct.price,
                }
              : cartProduct,
            );
          console.log('##currentCart', JSON.stringify(currentCart));
          return {
            cartProducts: currentCart,
          };
        });
        ...
      },
    }),
    {
      name: 'cartListProduct-local',
      getStorage: () => AsyncStorage,
    },
  ),
);

产品详情

 const addProductToCart = () => {
      let productOptionIds = allOptions
        .map(({id}: {id: number | string}) => id)
        .sort()
        .join(',');
      let currentProduct = {
        ...item,
        id: item.id,
        product_id: item.id,
        quantity: currentQuantity,
        price: updatedPrice,
        productTotalPrice: updatedPrice * currentQuantity,
        selectedOptions: allOptions,
        productOptionIds: productOptionIds,
      };
      setAddToCartLoading(true);
      if (
        !cartProductList.some((alreadyExist) => alreadyExist.id === item.id)
      ) {
        addToCart(currentProduct);
        Alert.alert(t('addedSuccessfully'));
        setAddToCartLoading(false);
      } else {
        checkProductOptionsExist(currentProduct, currentQuantity);
        Alert.alert(t('addedSuccessfully'));
      }
  };

效用

export const areEqual = (a: arrayProps = [], b: arrayProps = []): boolean => {
  // compare length of arrays
  if (a.length !== b.length) {
    return false;
  }
  // get ids set in b
  const idsSetInB = new Set(b.map(({id}: {id: number | string}) => id));
  console.log('idsSetInB', idsSetInB);
  // iterate over a, and check if the id of an item is not in b
  for (let {id} of a) {
    if (!idsSetInB.has(id)) {
      return false;
    }
  }
  // if it passes all the items, return true
  return true;
};
4

1 回答 1

1

我只是在产品详细信息中添加支票,而不是在商店中,

首先,从购物车中获取目标产品,这样我就可以在这里根据 optionsID 检查它是否存在,如果返回未定义,这意味着产品+选项,而不是在购物车中,所以我将它添加为单独的产品,否则我更新数量和效果很好。

也许我不能在商店本身这样做checkProductOptionsExist,(如果你有任何解释请告诉我)

如果你有更好的主意,请这样做;)

...
if (
    !cartProductList.some((alreadyExist) => alreadyExist.id === item.id)
  ) {
    addToCart(currentProduct);
    Alert.alert(t('addedSuccessfully'));
    setAddToCartLoading(false);
}
else {
        let res = cartProductList.find(
          (currentProd) =>
            currentProd.product_id === currentProduct.product_id &&
            currentProd.productOptionIds === currentProduct.productOptionIds, // or areEqual FC ;)
        );
        res != null
          ? updateProductQuantity(currentProduct, currentQuantity)
          : addToCart(currentProduct);
        setAddToCartLoading(false);
        Alert.alert(t('addedSuccessfully'));
  }

店铺

....
updateProductQuantity: (
        product: ProductProps,
        updatedQuantity: number,
      ) => {
        set((prev) => {
          let currentCart = prev.cartProducts.map((cartProduct) =>
            cartProduct.id === product.id &&
            areEqual(cartProduct.selectedOptions, product.selectedOptions)
              ? {
                  ...product,
                  quantity: cartProduct?.quantity! + updatedQuantity,
                  productTotalPrice:
                    (cartProduct?.quantity! + updatedQuantity) *
                    cartProduct.price,
                }
              : cartProduct,
          );
          return {
            cartProducts: currentCart,
          };
        });
      },
....
于 2021-06-05T16:24:08.183 回答