javascript - 您正在导入一个需要 useState 的组件。它仅在客户端组件中有效,但其父组件均未标记为 "use client"

标签 javascript reactjs next.js

用于处理文件上传的简单组件在 Next.js 的应用程序目录中抛出以下错误:

You're importing a component that needs useState. It only works in a Client Component, but none of its parents are marked with "use client", so they're Server Components by default.

import { useState } from "react";

export default function FileUploader() {
  const [files, setFiles] = useState([]);

  return (
    <div>
      Hello World
    </div>
  );
}

最佳答案

app目录下,Next.js默认使用Server Components ,其中 JSX 被编译为“纯 HTML”并发送到浏览器。就像任何带有模板引擎的传统后端一样,例如带有 EJS 的 Express 和带有 Blade 的 Lavravel。这是为了更好的 SEO 和性能,您可以在 doc 上阅读:

Server Components allow developers to better leverage server infrastructure. For example, large dependencies that previously would impact the JavaScript bundle size on the client can instead remain entirely on the server, leading to improved performance.

并且服务器组件不应包含特定于前端的代码,例如,useStateuseEffect 等钩子(Hook)。如果您需要,您的组件或其父组件之一应该在顶部有 "use client"。这样,它就变成了 Client Component ,一个“普通”的 React 组件,正如我们目前所知。

"use client"; // this is a client component

import { useState } from "react";

export default function FileUploader() {
  const [files, setFiles] = useState([]);

  return (
    <div>
      Hello World
    </div>
  );
}

关于javascript - 您正在导入一个需要 useState 的组件。它仅在客户端组件中有效,但其父组件均未标记为 "use client",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74965849/

相关文章:

javascript - 将 React/Enzyme/Jest 与 Nextjs 一起使用时是否可以获取整页 html?

javascript - 有 Elixir 的 typescript 吗?

java - dhtmlxform.send 响应在警报提示中正确显示,但字符串比较不起作用

javascript - 如何在 HTML 中加载图像,如 iPad 网站从左向右滑动

javascript - 更改 nvd3 图表中的边距和填充

reactjs - ' react -i18next : withNamespaces is not a function' when testing

javascript - 如何在 Next JS 中使用对象数组进行路由?

reactjs - 在按钮单击中将动态参数传递给 React Query

json - Superagent:错误:解析器无法解析响应

javascript - React SwiperJs 自动播放不会使刷卡器自动刷卡