因此,我目前正在使用状态来确定用户是否已将商品添加到购物车中。除了当他们在“产品页面”(他们添加到购物车的页面)上时,它几乎可以完美地工作,并且他们刷新它清空了in_cart数组,但是如果我在添加它们后在主页上刷新了我我想要,这意味着它必须是产品页面代码中的内容,但无法弄清楚,这是产品页面代码:
const ProductPageBody = ({ products, in_cart, set_in_cart }) => {
//Keeps track of color user selects
const [color, setColor] = useState("");
//Keeps track of size user selects
const [size, setSize] = useState("Small");
//Filters out the product that the user selected
const { shirtName } = useParams();
const shirt = products.filter((product) => product.name === shirtName);
//Updates state size of shirt being selected
const updateSize = () => {
let select = document.getElementById("sizeSelect");
let text = select.options[select.selectedIndex].text;
setSize(text);
};
//Updates state color of shirt being selected
const updateColor = useCallback(async (userColor, shirt) => {
const shirtColorSource = await fetch(
`http://localhost:5000/products/${shirt.product_id}/${userColor}`
);
const shirtColor = await shirtColorSource.json();
console.log(shirtColor);
shirt.image = shirtColor[0].image;
setColor(userColor);
}, []);
//Occurs when ADD TO CART is clicked
const updateInCart = async (e) => {
e.preventDefault();
const newShirt = { ...shirt[0] };
newShirt["color"] = color;
newShirt["size"] = size;
const newList = in_cart.list.concat(newShirt);
const cost = newList.reduce((sum, shirt) => sum + shirt.price, 0);
set_in_cart({
list: newList,
totalcost: cost,
});
};
//Stores in cart items
useEffect(() => {
localStorage.setItem("inCartItems", JSON.stringify(in_cart));
}, [in_cart]);
及其状态所在的父级:
const Routes = () => {
const [products, setProducts] = useState([]);
const [in_cart, set_in_cart] = useState({
list: [],
totalCost: 0,
});
const getProducts = async () => {
try {
const response = await fetch("http://localhost:5000/products/");
const jsonData = await response.json();
setProducts(jsonData);
} catch (err) {
console.error(err.message);
}
if (localStorage.getItem("inCartItems")) {
set_in_cart(JSON.parse(localStorage.getItem("inCartItems")));
}
};
useEffect(() => {
getProducts();
}, []);
我们将不胜感激,谢谢!
答案 0 :(得分:0)
在Routes
中,添加一个效果,以便在购物车数据(in_cart
)更新时将其持久保存到localStorage。
useEffect(() => {
try {
localStorage.setItem("inCartItems", JSON.stringify(in_cart));
} catch(err) {
// do something if cart persistence fails
}
}, [in_cart]);