我正在尝试从localstorage加载初始状态以创建存储,但出现此错误:ReferenceError: localStorage is not defined
我的商店:
const store = createStore(reducer, {
userInfo: {
isLogged: false,
items: localStorage.getItem("@items") || []
}
})
答案 0 :(得分:0)
下一个js中未定义本地存储,因为它在服务器端呈现 要实现您的Redux,请使用Next js的样板。
此示例显示了如何将Redux与Redux的功能集成在一起 坚持使用Next.js。
使用redux为您的应用提供全局状态的优势。 您还需要一些状态值才能脱机使用。 有redux-persist,您可以使用它来保持状态 浏览器的本地存储。虽然有多种持久方法 您可以在任何文档中始终找到的状态。这是 如何将redux-persist与redux集成在一起的示例 使用Next.js的通用渲染方法。
答案 1 :(得分:0)
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);
}
}