🧩需要 use client(Next.js)
You're importing a component that needs "useState". This React Hook only works in a Client Component. To fix, mark the file (or its parent) with the "use client" directive.
在 Next.js 里,把按钮点击、状态(useState)这类要在浏览器里运行的功能,写在了服务器端用的文件里。
🤔 为什么会出现?
- 使用 useState、useEffect、onClick 等功能的文件,最上面没有写 "use client"
🔧 试试这样做
- 在使用这些功能的文件第一行加上 "use client"
- 最好不要整个页面都加,而是只把需要交互的部分拆成单独的组件,只在那里加上
🤖 这样问 AI
Next.js 里出现了下面的报错。请只把需要在浏览器里运行的部分拆成单独的组件,并在那个文件里加上 "use client" 来解决。 [在这里粘贴完整的报错]
把 [ ] 部分换成你的实际情况,报错前后的几行也尽量一起复制粘贴。
相关术语
同一分类的其他报错
- 试图读取空值(undefined)
Cannot read properties of undefined - 试图执行不是函数的东西
is not a function - 名称未定义
ReferenceError: … is not defined - 返回的不是 JSON(Unexpected token)
Unexpected token '<' … is not valid JSON - 服务器页面和浏览器页面不一致(Hydration)
Hydration failed - 无限重复渲染(Too many re-renders)
Too many re-renders - 列表缺少 key
Each child in a list should have a unique "key" prop - 函数无限调用自己(调用栈溢出)
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