javascript - 无效的挂钩调用。钩子只能在函数组件的主体内部调用。有任何想法吗?
问题描述
老实说,我已经在现有的问题中寻找答案,但这完全是个谜。
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>
解决方案
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>
推荐阅读
- html - GitHub Pages - 图片未加载 - 404 错误
- javascript - 未定义的角度属性“长度”
- java - IntelliJ 添加框架支持缺少 Maven 选项
- firebase - 离子 rxjs 管道函数在 http 发布后没有被调用
- karate - 多部分文件不采用文件名的变量
- html - 根据选项选择将表单重定向到不同的 URL
- swift - 从子 ViewController 进行 Segue
- java - Swing JComboBox在选择新项目时获取上一个项目
- html - 我可以使用 jQuery 隐藏特定 html 页面上的元素吗?
- wordpress - (Word Press) Ultimate Member 插件:在登录页面更新标签