【问题标题】:Invalid Hook call in ReactReact 中的 Hook 调用无效
【发布时间】:2021-04-29 15:12:07
【问题描述】:

我很新反应并得到以下错误:

react-dom.development.js:14906 Uncaught Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

我想在提交表单时使用另一个组件。因此,在提交表单时,在文件 A 中,它使用了一个函数,在该函数中,它首先检查某些内容,然后再调用其他组件,例如:

ComponentName()

在组件上我有一些 useState 钩子:

function ComponentName() {
    const [state1, setState1] = useState('')
    const [state2, setState2] = useState('')
    const [state3, setState3] = useState('')

在页面加载的那一刻,我收到了这个错误,有谁知道怎么回事?

【问题讨论】:

  • 要显示组件 A 或组件 B(或隐藏/显示组件),请使用条件渲染;你不会自己调用组件函数。

标签: javascript reactjs react-hooks setstate


【解决方案1】:

你不调用组件函数,你将它们交给 React 并让 React 酌情调用它们。所以你永远不会在你的代码中写ComponentName()。相反,您将使用 <ComponentName /> 作为渲染另一个组件的一部分,或者对于 React 树的最顶层,作为您传递 ReactDOM.render 的 JSX 的一部分。 (或者当然,使用 React.createElement 而不是 JSX。)

您收到错误是因为如果您 调用 所示的组件函数,它不会被用作组件,因此您对钩子的调用没有组件实例可以在后面使用场景——因此是错误消息。

【讨论】:

  • 我尝试了不同的方式来调用 ComponentName,事实是,使用 ComponentName() 方式,是它向我展示某些东西的唯一方式。如果我使用 ,​​什么都不会显示
  • @Kwiznix - 学习一些 React 教程。例如,如果 ComponentName 是您的顶级组件,您将使用 ReactDOM.render(<ComponentName/>, document.getElementById("root")); (假设您的 HTML 中有一个带有 id="root" 的元素,您希望您的 React 树作为根)。如果您正在使用像 Create React App 这样的引导项目,他们可能已经为您完成了这项工作(在 index.jsxindex.tsx 中,在 CRA 的情况下,它假定您的应用程序的根是一个名为 App 的组件在文件App.jsx/App.tsx)。
  • 是的,我有一个 index.js 文件,这个文件有 ReactDOM.render(), document.getElementByID("root"));。在这个文件中,我使用 react-router-dom 路由到不同的页面,在其中一个页面上有一个表单,当提交表单时,我想对该表单的结果做一些事情,所以我想调用'ComponentName' 在那里做事,所以表单有一个onSubmit: functionName,功能就像const functionName = () => {<ComponentName/>},当我使用它时,ComponentName 文件中的 console.logs 不会显示在控制台中
猜你喜欢
  • 2021-03-01
  • 1970-01-01
  • 2023-02-14
  • 2020-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多