简体   繁体   中英

Invalid Hook call in React

I'm quite new to react and get the following error:

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

I want to use another component when a form is submit. so in file A when the form is submit, is uses a function where is first checks something before calling the other component like:

ComponentName()

On the component I have some useState hooks:

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

at the moment the page is loading i am getting this error, does anyone know whats wrong?

You don't call component functions, you give them to React and let React call them as appropriate. So you'd never write ComponentName() in your code. Instead, you'd use <ComponentName /> as part of rendering another component or, for the very top-level of the React tree, as part of the JSX you're passing ReactDOM.render . (Or of course, use React.createElement rather than JSX.)

You're getting the error because if you call the component function as you've shown, it's not being used as a component, so your calls to hooks have no component instance to use behind the scenes — hence the error message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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