NextJS 与 redux 按预期运行,但它给出警告文本内容不匹配

0 session-storage reactjs redux next.js

我正在使用 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,
});
Run Code Online (Sandbox Code Playgroud)

这是我的页面代码:


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>
  );
}
Run Code Online (Sandbox Code Playgroud)

有人有解决这个问题的方法吗?

Iva*_* V. 5

当您检查window对象是否存在时(如果不存在,则您正在服务器上运行)。问题是server渲染值是,0而浏览器渲染值是25。发生这种情况是因为该值立即在浏览器中计算出来25(首先在浏览器中呈现)。

您将需要更改代码以将计算推迟到组件安装之后,因此初始browser值也可以0使用useEffect仅在浏览器中运行的来计算新值。