Skip to content

警告: 文本内容做 不 match. 服务器: 'X' 客户端: 'Y'

错误信息

                文本内容做 不 match. 服务器: 'X' 客户端: 'Y'
              

快速摘要

HTML rendered on 服务器 doesn't match 什么 React 渲染 on 客户端期间 hydration, causing mismatch 警告.

为什么发生

  • Using Date.现在(), Math.random(), or other 非-deterministic 值 in 渲染

  • 浏览器-仅 APIs (window, localStorage) used 期间 SSR

  • 不同数据 on 服务器对比客户端 (e.g., 用户会话)

  • Improper use 的 useEffect for 客户端-仅渲染

最小示例

✗ 错误代码
function Clock() {
  return <div>{new Date().toLocaleTimeString()}</div>; // Different on server and client!
}
✓ 修复代码
function Clock() {
  const [time, setTime] = useState(null);
  useEffect(() => {
    setTime(new Date().toLocaleTimeString());
  }, []);
  return <div>{time || "Loading..."}</div>;
}

Moving Date call 到 useEffect ensures 它仅 运行 on 客户端, avoiding 服务器/客户端 mismatch.

如何诊断

  • Look for Date.现在(), Math.random(), or Date in 渲染

  • 检查 for window/document/localStorage usage in 渲染

  • Compare 服务器 and 客户端输出到 查找 difference

如何修复

  • Move 非-deterministic code 到 useEffect (运行仅 on 客户端)

  • Use typeof window !== 'undefined' guards for 浏览器 APIs

  • Use suppressHydrationWarning for intentional differences

  • 渲染加载状态直到客户端-边数据是 ready

如何预防

  • 从不 use 非-deterministic 值 in 渲染

  • Guard 浏览器-仅 APIs 使用 typeof 检查

  • Use useEffect for 客户端-仅边 副作用

相关资源

相关术语

相关课程

← 返回语言