无法在 zustand 中同步更新的 Products List 数组?
can't synchronise the updated Products List array in zustand?
我想解释一下我的用例,以便您能很好地理解它
当用户将产品 (product_id = 1) 两次添加到购物车并且产品具有相同的选项(红色,xl)时,我有购物车和产品我增加了数量,
如果用户添加了相同的 (product_id = 1) 但有其他选项(绿色,xl),我会将此产品作为单独的产品添加到购物车。
现在效果很好!
但是当用户在添加了以上2个产品后,再次使用相同的选项(红色,xl)添加相同的产品时,它被添加为一个单独的产品!
如果之前存在的产品选项应该增加数量,否则我希望将其单独添加。
我试过的
将选项 ID 添加到产品中 属性 并检查它之前是否存在然后处理我想要的但它不能正常工作并添加第三个产品作为一个单独的产品!
代码片段
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;
};
我只是在产品详情中添加支票,而不是在商店中,
首先,从购物车中获取目标产品,这样我就可以根据 optionsID 检查它之前是否存在,如果 return 未定义,这意味着产品 + 选项,不在购物车中,所以我将它作为单独的产品添加,否则我会更新数量并且效果很好。
Maybe I can't do this in the store itself checkProductOptionsExist
, (if u have any explanation tell me please)
如果您有更好的想法,请采纳 ;)
...
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,
};
});
},
....
我想解释一下我的用例,以便您能很好地理解它
当用户将产品 (product_id = 1) 两次添加到购物车并且产品具有相同的选项(红色,xl)时,我有购物车和产品我增加了数量,
如果用户添加了相同的 (product_id = 1) 但有其他选项(绿色,xl),我会将此产品作为单独的产品添加到购物车。
现在效果很好!
但是当用户在添加了以上2个产品后,再次使用相同的选项(红色,xl)添加相同的产品时,它被添加为一个单独的产品!
如果之前存在的产品选项应该增加数量,否则我希望将其单独添加。
我试过的
将选项 ID 添加到产品中 属性 并检查它之前是否存在然后处理我想要的但它不能正常工作并添加第三个产品作为一个单独的产品!
代码片段
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;
};
我只是在产品详情中添加支票,而不是在商店中,
首先,从购物车中获取目标产品,这样我就可以根据 optionsID 检查它之前是否存在,如果 return 未定义,这意味着产品 + 选项,不在购物车中,所以我将它作为单独的产品添加,否则我会更新数量并且效果很好。
Maybe I can't do this in the store itself
checkProductOptionsExist
, (if u have any explanation tell me please)
如果您有更好的想法,请采纳 ;)
...
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,
};
});
},
....