浏览器的本地存储不断重置为未定义

时间:2020-10-20 16:03:40

标签: javascript reactjs react-hooks local-storage

我使用 ReactJs ,我想将更多项目推送到localstorage中已存在的项目,但是每次我重新加载localstorage都会重置为undefined ...

   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")
      }

   })

2 个答案:

答案 0 :(得分:0)

您要做的第一件事是将购物车商品设置为本地存储

假设cartItems是一个数组,并且是一个状态; <​​/ p>

     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])

答案 1 :(得分:0)

将您的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));
   });