当我单击 addproduct 时,它会给出未定义的错误。这是我的 ProductDetails.js 代码 为什么产品设置为 localstorage 是未定义的
import axios from "axios";
import React, { useEffect, useState } from "react";
import { NavLink, useParams } from "react-router-dom";
import { useDispatch } from "react-redux";
import { addToCart } from "../Redux/action/action";
//import { useSelector } from "react-redux";
import { FaStar } from "react-icons/fa";
import Skeleton from "react-loading-skeleton";
const cartItemsFromStorage =
JSON.parse(localStorage.getItem("CartItems")) || [];
const ProductDetails = () => {
const { id } = useParams();
//const cartItems = useSelector((state) => state.handleCart);
const [isLoading, setIsLoading] = useState(false);
const [product, setProduct] = useState(cartItemsFromStorage);
const dispatch = useDispatch();
useEffect(() => {
const fetchProduct = async () => {
try {
setIsLoading(true);
const { data } = await axios.get(
`https://fakestoreapi.com/products/${id}`
);
setProduct(data);
} catch (error) {
console.error("Error fetching product:", error);
} finally {
setIsLoading(false);
}
};
fetchProduct();
}, [id]);
const addProduct = (product) => {
if (product) {
// Update the Redux store
dispatch(addToCart(product));
// Retrieve existing cart items from localStorage
const existingCartItemsJSON = localStorage.getItem("CartItems");
const existingCartItems = existingCartItemsJSON
? JSON.parse(existingCartItemsJSON)
: [];
// Ensure that existingCartItems is an array
if (!Array.isArray(existingCartItems)) {
console.error("Invalid existingCartItems:", existingCartItems);
return;
}
// Add the new product to the existing cart items
const updatedCartItems = [...existingCartItems, product];
// Store the updated cart items back in localStorage
localStorage.setItem("CartItems", JSON.stringify(updatedCartItems));
} else {
console.error("Invalid product:", product);
}
};
const ShowProducts = () => (
<div className="d-flex row" key={product.id}>
<div className="col-md-6 col-sm-3 mt-5">
<img
src={product.image}
alt={product.title}
height="400px"
width="400px"
/>
</div>
<div className="col-md-6 mt-5">
<h4 className="text-uppercase text-black-50">{product.category}</h4>
<h1 className="display-5">{product.title}</h1>
<p className="lead fw-bolder">
Rating {product.rating && product.rating.rate}
<FaStar />
</p>
<h3 className="display-6 fw-bolder my-4">${product.price}</h3>
<p className="lead">{product.description}</p>
<button className="btn btn-primary" onClick={() => addProduct(product)}>
Add to Cart
</button>
<NavLink to="/MyCart" className="btn btn-outline-dark ms-2">
Go to Cart
</NavLink>
</div>
</div>
);
return (
<>
<div className="container py-5">
<div className="row">
{isLoading ? (
<>
{" "}
<div className="col-md-6">
<Skeleton height={400} />
</div>
<div className="col-md-6">
<Skeleton width={300} height={50} />
<Skeleton height={75} />
<Skeleton width={25} height={150} />
<Skeleton height={50} />
<Skeleton height={150} />
<Skeleton height={50} width={100} />
<Skeleton height={50} width={100} />
</div>
</>
) : (
product && <ShowProducts />
)}
</div>
</div>
</>
);
};
export default ProductDetails;
这是我的Reducer.js代码,我在其中定义了addToCart()函数
import { ADD_TO_CART, REMOVE_FROM_CART } from "../action/action-type";
const cart = []
const handleCart = (state = cart, action) => {
const product = action.payload;
switch (action.type) {
case ADD_TO_CART:
const existingProduct = state.find((item) => item.id === product.id);
if (existingProduct) {
return state.map((item) =>
item.id === product.id ? { ...item, qty: item.qty + 1 } : item
);
} else {
const product = action.payload;
return [
...state,
{
...product,
qty: 1,
},
];
}
case REMOVE_FROM_CART:
const existingProductToRemove = state.find(
(item) => item.id === product.id
);
if (existingProductToRemove.qty === 1) {
return state.filter((item) => item.id !== product.id);
} else {
return state.map(
(item) =>
item.id === product.id ? { ...item, qty: item.qty - 1 } : item,
localStorage.setItem("CartItems", JSON.stringify(state.cart))
);
}
default:
return state;
}
};
export default handleCart;
当我单击 addProduct 时,它给出了未定义错误,我认为它从本地存储中获取未定义的项目或未定义的数据集。 请有人给我提供解决方案,解决了我被困了两天的问题。
您的代码中需要考虑一些事项。
在组件 ProductDetails.js 中,产品的初始状态被设置为 cartItemsFromStorage,它是在组件外部定义的。这可能会导致未定义的错误。您似乎打算使用空对象 {} 来初始化产品。您应该替换这一行:
const [product, setProduct] = useState(cartItemsFromStorage);
与
const [product, setProduct] = useState({});
addProduct 函数需要一个参数product,但它的调用没有任何参数。当您在 JSX 按钮的 onClick 处理程序中调用它时,请确保将产品对象作为参数传递:
<button className="btn btn-primary" onClick={() => addProduct(product)}>Add to Cart</button>
在 Redux 减速器 (handleCart.js) 中,REMOVE_FROM_CART 案例中包含以下行:
localStorage.setItem("CartItems", JSON.stringify(state.cart));
您尝试将更新的购物车商品存储到 localStorage 中,但您使用的是不存在的 state.cart。应该是:
localStorage.setItem("CartItems", JSON.stringify(state));
希望这能解决您的错误。但也让你的API调用有一些数据。