[英]React, getting Error: Invalid hook call. Hooks can only be called inside of the body of a function component
Can anyone help me with React Hooks basics, I am relatively new and couldn't find proper help online任何人都可以帮助我了解 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
I get error on const navigate = useNavigate()
saying:我在
const navigate = useNavigate()
上收到错误消息:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component
What they want for useNavigate
(and all hooks) is to be called only at the top level of a React component or a custom hook.他们想要的
useNavigate
(和所有钩子)只能在 React 组件或自定义钩子的顶层调用。
Don't call Hooks inside loops, conditions, or nested functions.
不要在循环、条件或嵌套函数中调用 Hook。 Instead, always use Hooks at the top level of your React function, before any early returns.
相反,在任何提前返回之前,始终在 React 函数的顶层使用 Hooks。
See Rules of Hooks for more.
有关更多信息,请参阅挂钩规则。
A solution to your problem could be calling const navigate = useNavigate()
in the component where you will use GoogleAuth
, and pass navigate
as parameter.您的问题的解决方案可能是在您将使用
GoogleAuth
的组件中调用const navigate = useNavigate()
,并将navigate
作为参数传递。 As an example like so:举个例子:
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.