NextJS 刷新时 localStorage 重置为空

Ele*_*all 1 javascript reactjs next.js

我的 next.js 应用程序中有一个使用 Context 的购物车系统。

我用以下方式定义我的购物车useState

const [cartItems, setCartItems] = useState([]);

然后我用它useEffect来检查和更新 localStorage:

useEffect(() => {
    if (JSON.parse(localStorage.getItem("cartItems"))) {
      const storedCartItems = JSON.parse(localStorage.getItem("cartItems"));
      setCartItems([...cartItems, ...storedCartItems]);
    }
  }, []);

  useEffect(() => {
    window.localStorage.setItem("cartItems", JSON.stringify(cartItems));
  }, [cartItems]);
Run Code Online (Sandbox Code Playgroud)

这可以很好地将项目存储在 localStorage 中,但是当我刷新时,它将cartItemslocalStorage 中的项目重置为空数组。我见过一些答案,您可以在设置购物车状态之前获取 localStorage 项目,但这会localStorage is not defined在下一步中引发错误。我怎样才能做到这一点?

Sam*_*jig 5

setCartItemscartItems设置下一个渲染的值,因此在初始渲染中它是[]在第二个渲染期间useEffect

您可以通过存储一个引用(状态更改时不会重新渲染)来确定是否是第一次渲染来解决此问题。

import React, { useState, useRef } from "react";

// ...

// in component

const initialRender = useRef(true);

useEffect(() => {
    if (JSON.parse(localStorage.getItem("cartItems"))) {
        const storedCartItems = JSON.parse(localStorage.getItem("cartItems"));
        setCartItems([...cartItems, ...storedCartItems]);
    }
}, []);

useEffect(() => {
    if (initialRender.current) {
        initialRender.current = false;
        return;
    }
    window.localStorage.setItem("cartItems", JSON.stringify(cartItems));
}, [cartItems]);
Run Code Online (Sandbox Code Playgroud)