【发布时间】:2021-01-15 17:01:35
【问题描述】:
我正在使用 NextJS 跟踪示例代码 redux 工具包(计数器)并尝试将状态存储到 sessionStorage,它按预期运行但控制台发出警告"Warning: Text content did not match. Server: "0" Client: "25"
这是我的 redux 商店:
import counterReducer from "./counterSlice";
const initValue = () => {
let value = 0;
if (typeof window !== "undefined") {
if (sessionStorage.getItem("counter")) {
value = sessionStorage.getItem("counter");
}
}
return parseInt(value);
};
const preloadedState = {
counter: {
value: initValue(),
},
};
export default configureStore({
reducer: {
counter: counterReducer,
},
preloadedState,
});
这是我的页面代码:
import { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import useSWR from "swr";
import {
decrement,
increment,
incrementByAmount,
incrementAsync,
selectCount,
} from "../redux/counterSlice";
export default function Counter() {
let count = useSelector(selectCount);
const dispatch = useDispatch();
return (
<Layout>
<div
style={{ display: "grid", placeContent: "center", textAlign: "center" }}
>
<h1>Counter</h1>
<div style={{ display: "grid", gridAutoFlow: "column", gap: 50 }}>
<button onClick={() => dispatch(increment())}>Inc</button>
<h4>{count}</h4>
<button onClick={() => dispatch(decrement())}>Dec</button>
</div>
</div>
</Layout>
);
}
有人有解决这个问题的方法吗?
【问题讨论】:
标签: reactjs redux next.js session-storage