【问题标题】:can't synchronise the updated Products List array in zustand?无法在 zustand 中同步更新后的 Products List 数组?
【发布时间】:2021-06-05 15:31:00
【问题描述】:

我想解释一下我的用例,以便您更好地理解它

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

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

现在效果很好!

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

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

我尝试了什么

将选项 ID 添加到 Product 属性中并检查它之前是否存在,然后处理我想要的,但效果不佳,并将第三个产品添加为单独的产品!

Screen Record

代码 sn-p

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;
};

【问题讨论】:

  • 这里的代码好像不完整。你能提供一个简单的沙盒来展示你的演示吗?它不一定必须使用您正在使用的技术。
  • 嘿,@MajedBadawi 我解决了,检查下面的答案 :) 感谢您的关注

标签: javascript reactjs typescript react-native zustand


【解决方案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,
          };
        });
      },
....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-19
    • 2021-08-22
    • 1970-01-01
    相关资源
    最近更新 更多