我正在尝试在 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);