我正在寻找一个解决方案,如何正确地持有产品添加到购物车在会议中.目前我是这样解决的:
Page.tsx
const ProductPage = () => {
const { product, loading, error } = useProductData();
const { cart, addToCart: addToCartHook } = useCartItems(); // Use the addToCart function from the hook
const [isCartOpen, setIsCartOpen] = useState(false);
// Assuming there is an interface for your product/item
interface ProductItem {
databaseId: number;
// Other properties...
}
const handleAddToCart = (item: ProductItem) => {
// Use the addToCart function from the hook
addToCartHook(item);
// Add item to WooCommerce cart using GraphQL mutation
addToCart(item.databaseId, 1); // Assuming quantity is 1, adjust as needed
};
useEffect(() => {
// Open the cart when the cart is updated
if (cart.length > 0) {
setIsCartOpen(true);
}
}, [cart]);
const handleCloseCart = () => {
setIsCartOpen(false);
};
return (
以下是Hook useCartItems:
export const useCartItems = () => {
// Load cart from localStorage on hook initialization
const initialCart = JSON.parse(localStorage.getItem('cart')) || [];
const [cart, setCart] = useState(initialCart);
// Save cart to localStorage whenever it changes
useEffect(() => {
localStorage.setItem('cart', JSON.stringify(cart));
}, [cart]);
// Function to add an item to the cart
const addToCart = (item) => {
setCart([...cart, item]);
};
// Function to clear the entire cart
const clearCart = () => {
setCart([]);
};
// Function to remove a specific item from the cart
const removeFromCart = (itemId) => {
const updatedCart = cart.filter((item) => item.id !== itemId);
setCart(updatedCart);
};
// Calculate cart count
const cartCount = cart.length;
return {
cart,
cartCount,
addToCart,
clearCart,
removeFromCart,
};
};
这个钩子工作并检索购物车中的物品,但问题出在这部分功能上: Const InitialCart=JSON.parse(localStorage.getItem(‘cart’))||[];
此工作但Nextjs每次都返回错误:
ReferenceError: localStorage is not defined
at useCartItems (./lib/woocommerce/index.ts:454:36)
at Navbar (./components/layout/navbar/index.tsx:43:96)
459 |
460 | // Load cart from localStorage on hook initialization
> 461 | const initialCart = JSON.parse(localStorage.getItem('cart')) || [];
我不确定我是否应该这样写,或者也许有其他的解决方案.