nextjs ssr 导致客户端状态持续冲突

nextjs ssr cause client side state persist conflict

我使用 zustand 来管理我的状态。

我将宽度状态保存在用户本地存储中,然后重新加载,在控制台中,我看到这样的错误:

Prop style did not match. Server: "width:400px" Client: "width:385px"

因为默认状态是400,但是在客户端本地存储是385,加载的时候冲突了

当我尝试保持挂载和卸载组件的状态时,情况变得最糟,因为默认服务器状态是挂载,但客户端状态是卸载,这会导致客户端崩溃

就我而言,这个答案很有帮助。

https://github.com/vercel/next.js/issues/7417#issuecomment-660241345

When React do the rehydration phase, if the output rendered in the server side is different from the generated in the rehydration phase this makes React be confused and makes him render the output in a wrong way, so what you need to do is assure that the output generated by the server be exactly the same to the generated by the rehydration phase (that have access to browser apis, this is the reason why the output differs) and wait for the component to mount, that happens after the rehydration phase to make any changes based in-browser API or any other type of client-side data

你的情况

请注意,服务器端和客户端之间的初始状态必须始终相同,您可以在安装组件后安全地更改客户端状态(和反应树)。

import { useState, useEffect } from "react";

// default width for SSR
const defaultWidth = 400;

const useWidth = () => {
  const [width, setWidth] = useState(defaultWidth);
  // onMounted
  useEffect(() => {
    if (typeof window === "undefined") return;
    setWidth(window.innerWidth);
  }, []);

  return width;
};