首页 > 解决方案 > 无效的挂钩调用。钩子只能在函数组件的主体内部调用。有任何想法吗?

问题描述

老实说,我已经在现有的问题中寻找答案,但这完全是个谜。

Firebase.js

import * as firebase from "firebase/app";
import "firebase/auth";
import React, { useContext } from "react";
import { Auth } from "../contexts/AuthContext";

export const FirebaseLogout = async () => {
  const { state: auth, dispatch } = useContext(Auth);
  const logout = await firebase
    .auth()
    .signOut()
    .then(
      dispatch({
        type: "LOGOUT",
      })
    )
    .catch((err) => {
      console.log(err);
      return err;
    });
  return;
};

我的页面.js

import { FirebaseLogout } from "../../../firebase/Firebase";
...Stateless functional component with other non-relevant code between...
<Button onClick={() => FirebaseLogout()} type='primary'>
  {auth.user.uid ? "Logout" : "Sign up"}
</Button>

标签: javascripthtmlreactjsreact-hooksreact-context

解决方案


FirebaseLogout 是一个动作或处理程序,因此不能使用该useContext钩子。解决方案是将其制成 custok 挂钩或将上下文值作为参数传递

export const FirebaseLogout = async () => {

  const logout = await firebase
    .auth()
    .signOut()
    .then(
      dispatch({
        type: "LOGOUT",
      })
    )
    .catch((err) => {
      console.log(err);
      return err;
    });
  return;
};

我的页面.js

const contextValue = useContext(Auth);


  <Button onClick={() => FirebaseLogout(contextValue)} type='primary'>
     {auth.user.uid ? "Logout" : "Sign up"}
   </Button>

推荐阅读