我正在尝试在react中使用firebase进行身份验证。这是跟踪我的身份验证状态的组件。
import { useState} from "react";
function useAuth(fbAuth) {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const createEmailUser = (email, password) => fbAuth.createUserWithEmailAndPassword(email, password);
const signInEmailUser = (email, password) => fbAuth.signInWithEmailAndPassword(email, password);
const signOut = fbAuth.signOut();
fbAuth.onAuthStateChanged(async user=> {
if (user) {
await setIsAuthenticated(true);
console.log(isAuthenticated, "should be true")
return
} else {
await setIsAuthenticated(false);
console.log(isAuthenticated, "should be false")
return
}
});
return {isAuthenticated, createEmailUser, signInEmailUser, signOut};
}
export default useAuth
单击登录时,控制台日志为
2useAuth.js:13 false“应为真”
2useAuth.js:17 false“应该为false”
2useAuth.js:17 true“应为false”
4useAuth.js:17 false“应该为false”
发布于 2020-05-06 19:37:45
setIsAuthenticated
函数不返回promise,所以在这里使用await
实际上不会做任何事情。最重要的是,isAuthenticated
的值永远不会被修改(调用setIsAuthenticated
不会改变您在钩子开始处已经设置的变量的值)。基本上,在onAuthStateChanged
函数中执行console.log
是没有意义的,也不会做您期望的事情。如果您想更好地了解正在发生的事情,请尝试在函数的开头放置一个console.log
,并只打印您希望它发生更改的事实。所以就像这样:
import { useState, useEffect } from "react";
function useAuth(fbAuth) {
const [isAuthenticated, setIsAuthenticated] = useState(false);
const createEmailUser = (email, password) => fbAuth.createUserWithEmailAndPassword(email, password);
const signInEmailUser = (email, password) => fbAuth.signInWithEmailAndPassword(email, password);
const signOut = fbAuth.signOut();
console.log('isAuthenticated', isAuthenticated)
//I'm assuming you only need to register the fbAuth.onAuthStateChanged
//callback once. So We use useEffect with an empty array to have it
//only run the first time this is rendered.
useEffect(() => {
fbAuth.onAuthStateChanged(async user=> {
if (user) {
setIsAuthenticated(true);
console.log('isAuthenticated should be true after this')
} else {
setIsAuthenticated(false);
console.log('isAuthenticated should be false after this')
}
});
}, [])
return {isAuthenticated, createEmailUser, signInEmailUser, signOut};
}
export default useAuth
然后你就会期望
//Initial render
isAuthenticated false
//Click log-in
isAuthenticated should be true after this
isAuthenticated true
//Click log-out
isAuthenticated should be false after this
isAuthenticated false
发布于 2020-05-06 19:39:06
我看不出这里有什么问题。您可以在值更改之前获取该值。要访问最新的状态,可以使用useEffect钩子。你也没有问任何问题,比如你的问题是什么,你期望什么?
https://stackoverflow.com/questions/61643629
复制相似问题