Next.js项目中使用Redux Toolkit实现状态持久化至localStorage及‘localStorage is not defined’报错解决
解决Redux Toolkit中
localStorage is not defined的问题 Hey there! That localStorage is not defined error is super common when working with Redux in SSR/SSG environments (like Next.js), and it's easy to fix once you know why it's happening.
为什么会出现这个错误?
localStorage是浏览器专属的API,不存在于服务器端或者非浏览器运行环境中。你的代码在cartSlice.jsx顶部直接调用localStorage.getItem('cart'),如果你的项目是SSR/SSG框架(比如Next.js),Redux slice会在服务器端初始化执行,这时候localStorage还不存在,就会抛出这个错误。
快速修复方案
我们只需要在访问localStorage之前,先判断当前环境是否是浏览器(即window对象是否存在),这样就能避免在服务器端执行时出错。
修改后的cartSlice.jsx代码:
import {v4 as uuid} from "uuid"; import {createSlice} from "@reduxjs/toolkit"; // 仅在浏览器环境下读取localStorage的初始数据 const initialState = typeof window !== 'undefined' ? JSON.parse(localStorage.getItem('cart')) || [] : []; export const cartSlice = createSlice({ name: 'shoppingCart', initialState, reducers: { addToCart: (state, action) => { const product = action.payload; const productInCart = state.find(item => item.id === product.id && item.color === product.color && item.size === product.size && item.material === product.material ); if (productInCart) { const cartProductIndex = state.findIndex(item => item.id === product.id); state[cartProductIndex].quantity += product.quantity; } else { product['cartId'] = uuid(); return [product, ...state]; } // 仅在浏览器环境下保存到localStorage if (typeof window !== 'undefined') { localStorage.setItem('cart', JSON.stringify(state)); } } } })
关键修改点:
- 初始化state时:用
typeof window !== 'undefined'判断环境,只有在浏览器环境才读取localStorage,否则初始化为空数组。 - reducer中保存数据时:同样添加环境判断,确保只有在浏览器里才执行
localStorage.setItem。
更优雅的持久化方案(推荐)
如果你的项目需要长期维护,手动写localStorage操作会比较繁琐,推荐使用redux-persist库来自动处理Redux状态的持久化:
- 安装依赖:
npm install redux-persist - 在你的Redux store配置中,添加
persistReducer和persistStore - 在根组件中用
PersistGate包裹你的应用,确保持久化的状态加载完成后再渲染
这样就不用手动在每个reducer里写localStorage操作,库会自动帮你处理环境判断和数据同步。
内容的提问来源于stack exchange,提问作者Raju Ahammad
相关产品推荐
相关产品推荐

