簡體   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