【问题标题】:NextJS with redux running like as expected but it give warning Text content did not match带有redux的NextJS按预期运行,但它给出警告文本内容不匹配
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-05-01
      • 2019-03-03
      • 2022-10-13
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      相关资源
      最近更新 更多