使用 localstorage Redux + Next.js 加载初始状态 [英] Load the initial state with localstorage Redux + Next.js

查看:136
本文介绍了使用 localstorage Redux + Next.js 加载初始状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 localstorage 加载初始状态以创建存储,但出现此错误:ReferenceError: localStorage is not defined

我的商店:

const store = createStore(reducer, {用户信息: {isLogged: 假,项目:localStorage.getItem("@items") ||[]}})

解决方案

local storage 没有在 next js 中定义,因为它是在服务器端渲染的使用 Next js 的这个样板来实现你的 Redux.

Redux 持久化示例<块引用>

这个例子展示了如何将 Redux 与 Redux 的强大功能相结合坚持使用 Next.js.

利用 redux 为您的应用程序提供全局状态的优势.您还需要一些状态值可以离线使用.有 redux-persist 使用它你可以坚持你的状态浏览器的本地存储.虽然坚持的方式多种多样您总能在那里的文档中找到您的状态.这是如何将 redux-persist 与 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

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.

Redux Persist example

This example shows how to integrate Redux with the power of Redux Persist in Next.js.

With the advantage of having a global state for your app using redux. You'll also require some of your state values to be available offline. There comes redux-persist using which you can persist your states in browser's local storage. 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.

这篇关于使用 localstorage Redux + Next.js 加载初始状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆