【问题标题】:Load the initial state with localstorage Redux + Next.js使用 localstorage Redux + Next.js 加载初始状态
【发布时间】:2020-11-26 07:45:56
【问题描述】:

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

我的商店:

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

【问题讨论】:

  • 上面的代码似乎是在节点环境的服务器上运行的,那么你如何拥有 localStorage?所以首先检查窗口是否定义,以确定这个浏览器是否然后继续下一步

标签: javascript redux next.js


【解决方案1】:

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

Redux Persist example

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

利用 redux 为您的应用提供全局状态的优势。 您还需要一些状态值才能离线使用。 有 redux-persist 使用它你可以持久化你的状态 浏览器的本地存储。虽然有多种坚持的方式 您可以随时在文档中找到您的状态。这是 一个如何将 redux-persist 与 redux 集成的示例 使用 Next.js 的通用渲染方法。

【讨论】:

    【解决方案2】:

    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);
        }
    }

    【讨论】:

    • 在 Next.js 中,一切都是服务器端渲染的,如果初始渲染客户端与服务器端不匹配,则会出现 HTML 不匹配警告。页面的客户端版本也将被丢弃。所以我们不能单独使用这个方法来导致页面呈现不同。
    猜你喜欢
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 2018-08-25
    • 2021-12-23
    • 2021-01-02
    • 2019-09-03
    相关资源
    最近更新 更多