我的项目中有以下代码,我需要在实时单击时禁用 wislist 按钮。我能够禁用它,但在重新加载页面后它被禁用。我需要在单击按钮后立即执行此操作。这是我的js const talProps = useAddWishlistItem({ childSku: item.sku, sku: item.sku, query: WishlistPageOperations, mutation: wishlistItemOperations, product }); const { handleAddToWishlist, isAddToCartDisabled, hasError, isItemAdded } = talProps;这是我的按钮 <Button className={classes.btnWishlist} onClick={handleAddToWishlist} disabled={isItemAdded}> <img className={classes.WishlistIcon} src={WishlistIcon}/> </Button>isItemAdded 从 useAddWishlistItem 返回。useAddWishlistItem.jsexport const useAddWishlistItem = props => { const {mutation, query, product} = props; const {mutations} = mutation; const {addProductToWishlist} = mutations; const {queries} = query; const {getCustomerDetails} = queries; const productType = product.__typename; const [quantity] = useState(INITIAL_QUANTITY); const {data, err, load} = useQuery(getCustomerDetails); let wishListId; if (data) { const {customer} = data; const {wishlist} = customer; wishListId = wishlist.id; } const getIsItemAdded = (product) =>{ for (let i=0; i< data.customer.wishlist.items.length;i++){ if (data.customer.wishlist.items[i].product.url_key === product.url_key){ return true; } } } const [addItemsToWishlist, { error, loading:isAddSimpleLoading }] = useMutation(addProductToWishlist); const handleAddToWishlist = useCallback(async () => { const payload = { item: product, productType, quantity };
1 回答
慕桂英4014372
TA贡献1871条经验 获得超13个赞
isItemAdded仅当且仅当发生更改时才会重新计算product。还应该考虑是否data通过将其添加为 中的依赖项而发生更改useMemo()。
const getIsItemAdded = (product, data) => {
for (let i=0; i< data.customer.wishlist.items.length;i++){
if (data.customer.wishlist.items[i].product.url_key === product.url_key){
return true;
}
}
return false;
}
const isItemAdded = useMemo(
() => getIsItemAdded(product, data),
[product, data] // add data
)
添加回答
举报
0/150
提交
取消