简体   繁体   English

使用本地存储 Redux + Next.js 加载初始 state

[英]Load the initial state with localstorage Redux + Next.js

I'm trying to load the initial state from localstorage to create store, but i got this error: ReferenceError: localStorage is not defined我正在尝试从 localstorage 加载初始 state 以创建存储,但出现此错误: ReferenceError: localStorage is not defined

My store:我的店铺:

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

local storage is not defined in next js because it renders in server side to implement your Redux use this boiler Plate by Next js.本地存储未在 next js 中定义,因为它在服务器端呈现以实现您的 Redux 使用 Next js 的此样板。

Redux Persist example Redux 坚持例子

This example shows how to integrate Redux with the power of Redux Persist in Next.js.这个例子展示了如何将 Redux 与 Redux 的力量集成在 Next.js 中。

With the advantage of having a global state for your app using redux.使用 redux 为您的应用程序提供全局 state 的优势。 You'll also require some of your state values to be available offline.您还需要一些 state 值可以离线使用。 There comes redux-persist using which you can persist your states in browser's local storage.使用 redux-persist,您可以将状态保存在浏览器的本地存储中。 While there are various ways of persisting your states which you can always find in there documentation.虽然有多种方法可以保持您的状态,但您总能在文档中找到这些方法。 This is an example of how you can integrate redux-persist with redux along with Next.js's universal rendering approach.这是一个如何将 redux-persist 与 redux 以及 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); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM