错误"/>
任何人都请帮助我面临 json 未定义的错误
Json undefined error occurs in my web application 请尝试帮助我,因为我必须制作它的项目报告,时间只剩下几天了
import {createContext, useEffect, useState} from "react";
export const CartContext = createContext({});
export function CartContextProvider({children}) {
const ls = typeof window !== "undefined" ? window.localStorage : null;
const [cartProducts,setCartProducts] = useState([]);
useEffect(() => {
if (cartProducts?.length > 0) {
ls?.setItem('cart', JSON.stringify(cartProducts));
}
}, [cartProducts]);
useEffect(() => {
if (ls && ls.getItem('cart')) {
setCartProducts(JSON.parse(ls.getItem('cart')));
}
}, []);
function addProduct(productId) {
setCartProducts(prev => [...prev,productId]);
}
function removeProduct(productId) {
setCartProducts(prev => {
const pos = prev.indexOf(productId);
if (pos !== -1) {
return prev.filter((value,index) => index !== pos);
}
return prev;
},);
}
function clearCart() {
setCartProducts([]);
}
return (
<CartContext.Provider value={{cartProducts,setCartProducts,addProduct,removeProduct,clearCart}}>
{children}
</CartContext.Provider>
);
}
我需要帮助
回答如下:我不知道你到底得到了什么错误导致 json 未定义错误发生的各种原因,但也许你可以尝试检查 json 是否未定义,然后再像那样解析 json
if (typeof JSON !== 'undefined') {
ls?.setItem('cart', JSON.stringify(cartProducts));
}
更多推荐
任何人都请帮助我面临 json 未定义的错误
发布评论