You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js中使用LocalStorage遇问题,已做window判断仍无法解决

Next.js 中 LocalStorage 无法正常使用的问题排查与修复

你的代码里存在以下几个问题:

  • 条件判断语法错误:typeof window !== undefined 写法不对,typeof 返回的是字符串类型,正确写法应为 typeof window !== 'undefined'。
  • 初始值类型不匹配:cart 状态定义为数组类型,但服务器端 fallback 值给了空字符串 '',会触发类型报错,需改为空数组 []。
  • LocalStorage 键名混淆:cart 初始化时读取的是 wishlist 键,实际应该读取 cart 键。
  • wishlist 未做服务器端兼容:wishlist 的初始状态直接调用 localStorage,服务器端运行时会抛出错误,必须加上环境判断。

修正后的代码:

type productsTypeProps = {
  products: productsType[];
  cart?: string;
  wishlist?: string;
  fallbackValue?: any;
};

const ProductsList: FC<productsTypeProps> = ({ products }) => {
  // 修复cart的初始值:修正键名+正确环境判断+类型匹配
  const [cart, setCart] = useState<productsType[]>(
    typeof window !== 'undefined' ? JSON.parse(localStorage.getItem("cart") || "[]") : []
  );
  // 给wishlist加上服务器端环境判断
  const [wishlist, setWishlist] = useState<productsType[]>(
    typeof window !== 'undefined' ? JSON.parse(localStorage.getItem("wishlist") || "[]") : []
  );

  useEffect(() => {
    // 可选:添加判断确保在客户端执行,提升代码严谨性
    if (typeof window !== 'undefined') {
      localStorage.setItem("cart", JSON.stringify(cart));
      localStorage.setItem("wishlist", JSON.stringify(wishlist));
    }
  }, [cart, wishlist]);

  const addToCart = (product: productsType) => {
    setCart([...cart, product]);
  };

  const addToWishlist = (product: productsType) => {
    setWishlist([...wishlist, product]);
  };
};

额外说明:

Next.js 会在服务器端预渲染组件,此时 window 和 localStorage 均不存在,所有涉及浏览器 API 的操作必须先判断运行环境。useEffect 钩子仅在客户端执行,原本内部代码不会触发服务器错误,但加上环境判断能进一步避免极端场景下的问题。

内容的提问来源于stack exchange,提问作者Rashid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 09:36:10