繁体   English   中英

反应,得到错误:无效的钩子调用。 Hooks 只能在函数组件的主体内部调用

[英]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.

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