使用localstorage Redux+Next.js加载初始状态



我试图从本地存储加载初始状态以创建存储,但我得到了这个错误:ReferenceError: localStorage is not defined

我的商店:

const store = createStore(reducer, {
userInfo: {
isLogged: false,
items: localStorage.getItem("@items") || []
}
})

本地存储没有在next js中定义,因为它在服务器端呈现要实现您的Redux,请使用Next js的这个锅炉板。

Redux-Persist示例

此示例显示如何将Redux与Redux的强大功能集成坚持Next.js.

使用redux为您的应用程序提供全局状态的优势。您还需要一些状态值可以脱机使用。有redux-persistent,使用它可以将状态持久化浏览器的本地存储。虽然有各种方法可以坚持你可以在那里的文档中找到你的州。这是如何将redux-persistent与redux-along集成的示例使用Next.js的通用渲染方法。

const getStorLocal = (item) => {
if (typeof localStorage !== 'undefined') {
return localStorage.getItem(item);
}
return null;
}
const setStorLocal = (item, value) => {
if (typeof localStorage !== 'undefined') {
localStorage.setItem(item, value);
}
}

最新更新