![](/img/trans.png)
[英]Is browser's “localStorage.generator++” operator atomic?
[英]browser's localstorage keeps resetting to undefined
我使用ReactJs ,我想將更多項目推送到 localstorage 中已經存在的項目,但是每次我重新加載 localstorage 時都會重置為未定義...
React.useEffect(() => {
localStorage.setItem("cartItems", JSON.stringify(cartItems));
if (localStorage.getItem("cartItems") !== null) {
try {
let existing = localStorage.getItem("cartItems");
if (existing !== JSON.stringify(cartItems)) {
try {
let newExist = JSON.parse(existing).push(cartItems);
localStorage.setItem("cartItems", newExist);
} catch (e) {
console.log("NOOOO")
}
}
} catch (error) {
console.log("CARTITMES Localstorage is empty")
}
} else {
console.log("Null Cartitems in localstorea")
}
})
您要做的第一件事是將購物車項目設置為本地存儲
假設cartItems
是一個數組並且是一個狀態;
React.useEffect(() => {
// this is not necessary here
//localStorage.setItem("cartItems", JSON.stringify(cartItems));
if (localStorage.getItem("cartItems") !== null) {
try {
let existing = localStorage.getItem("cartItems");
//this is not the best way to compare Arrys of objects
if (existing !== JSON.stringify(cartItems)) {
try {
//let newExist = JSON.parse(existing).push(cartItems);
let newExist = [...JSON.parse(existing), ...cartItems];
localStorage.setItem("cartItems", JSON.stringify(newExist));
} catch (e) {
console.log("NOOOO")
}
}
} catch (error) {
console.log("CARTITMES Localstorage is empty");
localStorage.setItem("cartItems", JSON.stringify(cartItems));
}
} else {
console.log("Null Cartitems in localstorea");
localStorage.setItem("cartItems", JSON.stringify(cartItems));
}
},[cartItems])
像下面這樣分開你的 useEffect 調用:
//First you need to get data from the previous session which should be stored in localstorage already.
//We are using the key "cartItems" to identify the values we need
//if cartData exists then do something - (most likely JSON.parse(cartData)) if your goal is to work with the data that is stored
React.useEffect(() => {
const cartData = localstorage.getItem("cartItems")
if (cartData) {
try {
//Your Logic Here
}
} catch (error) {
console.log("CARTITMES Localstorage is empty")
}
} else {
console.log("Null Cartitems in localstorea")
}
}, []);
//Below you're stringifying your object and storing it in local storage
React.useEffect(() => {
localStorage.setItem("cartItems", JSON.stringify(cartItems));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.