Nextjs Localstorage和购物车的上下文
我正在开发一个购物车系统,问题是,当我向购物车中添加产品时,它在上下文和局部存储中起作用。但是,当我刷新时,数据就消失了。
export const DataContext = createContext();
export const DataProvider = ({ children }) => {
const [cart, setCart] = useState([]);
const [state, dispatch] = useReducer(AppReducer, cart);
useEffect(() => {
const cartData = JSON.parse(localStorage.getItem("cart"));
if (cartData) {
setCart(cartData);
}
}, []);
useEffect(() => {
localStorage.setItem("cart", JSON.stringify(cart));
// Cookies.set("cart", cart, { expires: 1 / 24 });
// let products = Cookies.get("cart");
// console.log(products);
}, [cart]);
const addToCart = (newProduct) => {
setCart((prev) => [...prev, newProduct]);
};
return (
<DataContext.Provider value={{ cart, setCart, addToCart }}>
{children}
</DataContext.Provider>
);
};
然后,我只是在我的产品详细信息页面中导入addtocart
函数,然后将产品作为参数。
在Next.js中处理此问题比正常反应要差得多。我很高兴知道我做错了什么。
I'm developing a cart system and the problem is that, when I add a product to the cart, it works in context and localStorage; but, when I refresh, the data is gone.
export const DataContext = createContext();
export const DataProvider = ({ children }) => {
const [cart, setCart] = useState([]);
const [state, dispatch] = useReducer(AppReducer, cart);
useEffect(() => {
const cartData = JSON.parse(localStorage.getItem("cart"));
if (cartData) {
setCart(cartData);
}
}, []);
useEffect(() => {
localStorage.setItem("cart", JSON.stringify(cart));
// Cookies.set("cart", cart, { expires: 1 / 24 });
// let products = Cookies.get("cart");
// console.log(products);
}, [cart]);
const addToCart = (newProduct) => {
setCart((prev) => [...prev, newProduct]);
};
return (
<DataContext.Provider value={{ cart, setCart, addToCart }}>
{children}
</DataContext.Provider>
);
};
Then I just import addToCart
function in my product detail page and give the product as parameter.
Dealing with this in Next.JS is so much worse than normal React. I'll be glad to know what I'm doing wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
重新加载页面时,您的LocalStorage已被写入。尝试以下方法,以防止初始化时在本地存储中设置项目。
Your localstorage has been writen when you reload the page. Try the following way to prevent set item in localstorage when init.