簡體   English   中英

使用本地存儲 Redux + Next.js 加載初始 state

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

我正在嘗試從 localstorage 加載初始 state 以創建存儲,但出現此錯誤: ReferenceError: localStorage is not defined

我的店鋪:

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

本地存儲未在 next js 中定義,因為它在服務器端呈現以實現您的 Redux 使用 Next js 的此樣板。

Redux 堅持例子

這個例子展示了如何將 Redux 與 Redux 的力量集成在 Next.js 中。

使用 redux 為您的應用程序提供全局 state 的優勢。 您還需要一些 state 值可以離線使用。 使用 redux-persist,您可以將狀態保存在瀏覽器的本地存儲中。 雖然有多種方法可以保持您的狀態,但您總能在文檔中找到這些方法。 這是一個如何將 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