我想在个人项目上使用JavaScript添加“添加到购物车”功能,方法是在单击时将每个食物信息保存到本地存储,但会收到此“ TypeError:将圆形结构转换为JSON”错误
我尝试了fast-safe-stringify和Circular-json包,但无济于事
export const addFood = (food, next) => {
let cart = [];
if (typeof window !== "undefined") {
if (localStorage.getItem("cart")) {
cart = JSON.parse(localStorage.getItem("cart"));
}
cart.push({
...food,
count: 1
});
cart = Array.from(new Set(cart.map(f => f._id))).map(id => {
return cart.find(f => f._id === id);
});
const cartToString = JSON.stringify(cart);
localStorage.setItem("cart", cartToString);
next();
}
};
TypeError: Converting circular structure to JSON
--> starting at object with constructor 'FiberNode'
| property 'stateNode' -> object with constructor 'HTMLButtonElement'
--- property '__reactInternalInstance$v1zqxvbiiip' closes the circle
addFood
src/components/layouts/cartHelpers.js:16
13 | cart = Array.from(new Set(cart.map(f => f._id))).map(id => {
14 | return cart.find(f => f._id === id);
15 | });
> 16 | const cartToString = JSON.stringify(cart);
| ^ 17 | localStorage.setItem("cart", cartToString);
18 | next();
19 | }