【问题标题】:Next.js persistent state with React hooks and localStorageNext.js 具有 React 钩子和 localStorage 的持久状态
【发布时间】:2020-05-10 03:08:36
【问题描述】:

我正在尝试在 Next.js SSR 应用程序中使用 localStorage 和 React 挂钩创建持久状态,一切看起来都不错,但是当我在更新数据后重新加载页面时出现错误:

警告:文本内容不匹配。服务器:“0” 客户端:“5”

我能做些什么来修复它?这是我的代码:

import React, { createContext, useContext, useReducer } from 'react';
import Reducer from '../utils/Reducer';
const StoreContext = createContext();

let defaultState = {
  count: 0, 
  message: "",
  pageView: 0,
};

export const StoreProvider = ({ children }) => {

  const [state, dispatch] = useReducer(Reducer, {}, () => {

    const localData = process.browser ? localStorage.getItem('state') : null
    return localData ? JSON.parse(localData) : defaultState
  });

  return (
    <StoreContext.Provider value={{state, dispatch}}>
      {children}
    </StoreContext.Provider>
  )
}

export const useStore = () => useContext(StoreContext);

Demo in codesandbox

【问题讨论】:

标签: reactjs react-hooks next.js use-reducer


【解决方案1】:

出现该警告是因为当您的 应用程序使用客户端(浏览器)中呈现的 SSR。

这是因为你的默认值为 0,而 localstorage 将在客户端(浏览器)中工作,所以在你的应用程序获取数据后,它会自动从 localstorage 呈现值,但现在的值与你呈现的默认值不同来自 SSR。

您可以尝试@bcjohn 的评论建议,使用Effect react hooks 来更新值。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2020-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-30
    相关资源
    最近更新 更多