Javascript 为什么我的反应状态没有正确改变?
我正在尝试在react中使用firebase进行身份验证。 这是跟踪我的身份验证状态的组件Javascript 为什么我的反应状态没有正确改变?,javascript,reactjs,firebase,firebase-authentication,Javascript,Reactjs,Firebase,Firebase Authentication,我正在尝试在react中使用firebase进行身份验证。 这是跟踪我的身份验证状态的组件 import { useState} from "react"; function useAuth(fbAuth) { const [isAuthenticated, setIsAuthenticated] = useState(false); const createEmailUser = (email, password) => fbAuth.cr
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“应该是true”
2useAuth.js:17 false“应该是false”
2useAuth.js:17 true“应该是false”
4useAuth.js:17 false“应该是false”函数的
setIsAuthenticated
不会返回一个承诺,因此在这里使用wait
实际上没有任何作用。最重要的是,isAuthenticated
的值永远不会被修改(调用setIsAuthenticated
不会更改钩子开头已经设置的变量的值)。基本上,在您的onAuthStateChanged
函数中执行console.log
是没有意义的,也不会做您期望的事情。如果您想更好地了解正在发生的事情,请尝试在函数开头添加一个console.log
,然后打印您希望它发生更改的事实。比如说:
从“react”导入{useState,useffect};
函数useAuth(fbAuth){
const[isAuthenticated,setIsAuthenticated]=useState(false);
const createEmailUser=(电子邮件,密码)=>fbAuth.createUserWithEmailAndPassword(电子邮件,密码);
const signInEmailUser=(电子邮件,密码)=>fbAuth.signInWithEmailAndPassword(电子邮件,密码);
const signOut=fbAuth.signOut();
console.log('isAuthenticated',isAuthenticated)
//我假设您只需要注册fbAuth.onAuthStateChanged
//回调一次。所以我们使用useffect和一个空数组来实现它
//仅在第一次渲染时运行。
useffect(()=>{
fbAuth.onAuthStateChanged(异步用户=>{
如果(用户){
setIsAuthenticated(真);
console.log('在此之后isAuthenticated应为true')
}否则{
setIsAuthenticated(假);
console.log('在此之后isAuthenticated应为false')
}
});
}, [])
返回{isAuthenticated,createEmailUser,signInEmailUser,signOut};
}
导出默认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
我看这里没什么问题。您是在更改值之前获取该值的用户。要访问最新状态,可以使用钩子。
此外,您还没有问过任何问题,比如您的问题是什么,您希望得到什么?我想使用isAuthenticated进行受保护的路由验证。若isAuthenticated为true,则应允许用户进入,若未被允许,则应重新路由回登录页。核心问题是isAuthenticated没有更新,甚至在单击“登录”后,我也会被重新路由到登录页。@Rauno据我所知,如果有一个对象正在寻找isAuthenticated——类似于我在[react router]中找到的fakeAuth,我在过去使用的是使用redux,并将其作为道具传递到不同的组件中,但我不认为在这里这是必要的