![](/img/trans.png)
[英]React hook Error: Invalid hook call. Hooks can only be called inside of the body of a function component
[英]React, getting Error: Invalid hook call. Hooks can only be called inside of the body of a function component
任何人都可以幫助我了解 React Hooks 基礎知識,我比較新,無法在線找到適當的幫助
import React from 'react'
import { auth, provider } from "../../../firebaseSetup";
import { useNavigate } from "react-router-dom"
const GoogleAuth = async() => {
const navigate = useNavigate()
auth.signInWithPopup(provider).then(() => {
navigate('/home');
}).catch((error) => {
console.log(error.message)
})
}
export default GoogleAuth
我在const navigate = useNavigate()
上收到錯誤消息:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component
他們想要的useNavigate
(和所有鈎子)只能在 React 組件或自定義鈎子的頂層調用。
不要在循環、條件或嵌套函數中調用 Hook。 相反,在任何提前返回之前,始終在 React 函數的頂層使用 Hooks。
有關更多信息,請參閱掛鈎規則。
您的問題的解決方案可能是在您將使用GoogleAuth
的組件中調用const navigate = useNavigate()
,並將navigate
作為參數傳遞。 舉個例子:
import React from 'react'
import { auth, provider } from "../../../firebaseSetup";
import { useNavigate } from "react-router-dom"
const GoogleAuth = async(navigate) => {
auth.signInWithPopup(provider).then(() => {
navigate('/home');
}).catch((error) => {
console.log(error.message)
})
}
export default GoogleAuth
import GoogleAuth from "GoogleAuth";
const App = ()=>{
/*
here at the top level, not inside an if block,
not inside a function defined here in the component...
*/
const navigate = useNavigate();
useEffect(()=>{
GoogleAuth(navigate)
},[])
return <div></div>
}
export default App;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.