繁体   English   中英

React 中的 Hook 调用无效

[英]Invalid Hook call in React

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

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 中使用 function 在调用其他组件之前首先检查一些内容,例如:

ComponentName()

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

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

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

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

您收到错误是因为如果您调用组件 function 如您所示,它没有被用作组件,因此您对钩子的调用没有在幕后使用的组件实例 - 因此出现错误消息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM