React,获取错误:无效的钩子调用.钩子只能在函数组件的主体内部调用



有人能帮我学习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;

最新更新