🧩服务器页面和浏览器页面不一致(Hydration)
Hydration failed because the server rendered HTML didn't match the client.
服务器提前生成的页面和浏览器重新渲染的页面不一样,就会出现这个报错。在 Next.js 这类框架里很常见。
🤔 为什么会出现?
- 把当前时间、随机数这类每次渲染都会变的值直接显示在页面上
- 用 localStorage、window 这类只有浏览器才有的值来渲染页面
- HTML 结构写错了(比如在 p 标签里放了 div)
- 浏览器扩展程序(如翻译插件)改动了页面
🔧 试试这样做
- 在无痕窗口里看看是否也会出现(这样能判断是不是扩展程序导致的)
- 时间、随机数、浏览器里保存的值,要等页面显示出来之后(只在浏览器里)再显示
- 检查报错里提到的那部分 HTML 结构
🤖 这样问 AI
Next.js 里出现了下面的 Hydration 报错。请帮我找出服务器和浏览器渲染结果不一样的地方并修好。不要用关闭警告(suppress)的方式,请从根本原因上解决。 [在这里粘贴完整的报错]
把 [ ] 部分换成你的实际情况,报错前后的几行也尽量一起复制粘贴。
相关术语
同一分类的其他报错
- 试图读取空值(undefined)
Cannot read properties of undefined - 试图执行不是函数的东西
is not a function - 名称未定义
ReferenceError: … is not defined - 返回的不是 JSON(Unexpected token)
Unexpected token '<' … is not valid JSON - 无限重复渲染(Too many re-renders)
Too many re-renders - 列表缺少 key
Each child in a list should have a unique "key" prop - 需要 use client(Next.js)
Add the "use client" directive - 函数无限调用自己(调用栈溢出)
RangeError: Maximum call stack size exceeded - 渲染途中想去修改另一个组件
Cannot update a component while rendering a different component - 想把对象直接显示到页面上
Objects are not valid as a React child - 在服务器上用了浏览器功能(window is not defined)
ReferenceError: window is not defined - 把客户端组件写成了 async
async/await is not yet supported in Client Components - 外部图片地址没有被允许(next/image)
Invalid src prop … hostname is not configured under images - 需要用 Suspense 包起来(useSearchParams)
useSearchParams() should be wrapped in a suspense boundary - 没有处理的异步错误
Uncaught (in promise) - 读不懂日期(Invalid Date)
Invalid Date - 数字的位置显示 NaN
NaN