所以我想问这样的问题并寻求建议。如果有经验的开发人员给出他们的意见,我将非常高兴。预先感谢您<<3 So I have displayed the products from the user's api, if the user has made a favorite it should be a filled heart otherwise it should be an empty heart. But I don't know how to keep it so that it doesn't get lost in the refresh. In general, how do you store this type of data on the client side? There is also such a problem that, for example, in this code, it is completely fixed only after 1-2 refreshes, the first time it is opened, the favorite product comes with an empty heart.
import React, { useEffect, useState } from "react";
import heartOn from "../../assets/icons/heart-on.svg";
import heartFull from "../../assets/icons/Subtract.svg";
import { handleToggleWishlist } from "../../helpers";
import useAxios from "../../utils/useAxios";
import { toast } from "react-toastify";
const WishBtn = ({ ProductItemVideoCard }) => {
const axiosInstance = useAxios();
const [in_wishlist, set_in_wishlist] = useState(false);
useEffect(() => {
if (ProductItemVideoCard) {
set_in_wishlist(ProductItemVideoCard?.in_wishlist);
}
}, [ProductItemVideoCard]);
useEffect(() => {
const updateWishlistState = (event) => {
const { productId, status } = event.detail;
if (productId === ProductItemVideoCard?.id) {
set_in_wishlist(status);
}
};
window.addEventListener("wishlistUpdate", updateWishlistState);
return () => {
window.removeEventListener("wishlistUpdate", updateWishlistState);
};
}, [ProductItemVideoCard?.id]);
useEffect(() => {
if (ProductItemVideoCard) {
const wishlistState = JSON.parse(localStorage.getItem("wishlist")) || {};
set_in_wishlist(wishlistState[ProductItemVideoCard.id] || false);
}
}, [ProductItemVideoCard?.id]);
const handleWishlistToggle = async (productId) => {
const newStatus = await handleToggleWishlist(productId, axiosInstance);
if (newStatus !== null) {
set_in_wishlist(newStatus);
const wishlistState = JSON.parse(localStorage.getItem("wishlist")) || {};
if (newStatus) {
wishlistState[productId] = newStatus;
} else {
delete wishlistState[productId];
}
localStorage.setItem("wishlist", JSON.stringify(wishlistState));
const event = new CustomEvent("wishlistUpdate", {
detail: { productId, status: newStatus },
});
window.dispatchEvent(event);
} else {
console.log("Failed to update wishlist status");
}
};
if (!ProductItemVideoCard) return null;
return (
<img
src={in_wishlist ? heartFull : heartOn}
alt=""
onClick={() => handleWishlistToggle(ProductItemVideoCard.id)}
/>
);
};
export default WishBtn;
请注意,值 is_wishlist 来自应用程序,如果我喜欢它,则为 true,否则默认为 false
将其存储在
localstorage
中是一种方法。从您的代码来看,您似乎没有使用 in_wishlist
中的内容初始化 localstorage
状态。您可以使用没有依赖项的 useEffect
来执行此操作,然后它将在第一个渲染上运行(如果它在愿望列表中,则触发重新渲染),如下所示:
useEffect(() => {
if (ProductItemVideoCard) {
const localWishlist = JSON.parse(localStorage.getItem("wishlist")) || {};
set_in_wishlist(localWishlist[ProductItemVideoCard.id] || false);
}
}, []);
但我想说,为此,最好使用某种与用户帐户关联的服务器状态,以便它出现在不同的平台上。
而且
camelCase
比 JS 中的 snake_case
更传统。