【问题标题】:React, getting Error: Invalid hook call. Hooks can only be called inside of the body of a function component反应,得到错误:无效的钩子调用。 Hooks 只能在函数组件的主体内部调用
【发布时间】:2022-06-15 05:20:23
【问题描述】:

任何人都可以帮助我了解 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

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    他们想要 useNavigate(和所有钩子)只在 React 组件或自定义钩子的顶层调用。

    不要在循环、条件或嵌套函数中调用 Hooks。相反,总是在你的 React 函数的顶层使用 Hooks,在任何提前返回之前。

    请参阅Rules of 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;
    
    

    【讨论】:

    • 不要从常规 JavaScript 函数中调用 Hooks。相反,您可以: ✅ 从 React 函数组件调用 Hooks。 ✅ 从自定义 Hooks 调用 Hooks。
    猜你喜欢
    • 2020-12-06
    • 2020-01-18
    • 2021-03-12
    • 2021-03-30
    • 1970-01-01
    • 2021-02-08
    • 1970-01-01
    • 2020-06-22
    • 2019-09-07
    相关资源
    最近更新 更多