[英]reactjs: a context component function not updating its variable; usestate not working immediately?
I'm working on auth in my app, so I created a context to manage it:我正在我的应用程序中进行身份验证,因此我创建了一个上下文来管理它:
import React, { useState } from "react";
const AuthContext = React.createContext({
token: "",
isLoggedIn: false,
login: (token) => { },
logout: () => { },
});
export const AuthContextProvider = (props) => {
const [token, setToken] = useState(null);
const [userIsLoggedIn, setUserLoggedIn] = useState(false)
const loginHandler = async (token) => {
setToken(token);
setUserLoggedIn(true)
console.log(userIsLoggedIn) //prints false
};
const logoutHandler = () => {
setToken(null);
setUserLoggedIn(false)
};
const contextValue = {
token: token,
isLoggedIn: userIsLoggedIn,
login: loginHandler,
logout: logoutHandler,
};
return (
<AuthContext.Provider value={contextValue}>
{props.children}
</AuthContext.Provider>
);
};
export default AuthContext;
The problem is that when I call context.login('some token') from an outside component and then console.log(context.isLoggedIn) I get false the first time, but if I call context.login('some token') once again I get true.问题是当我从外部组件调用 context.login('some token') 然后 console.log(context.isLoggedIn) 我第一次得到 false ,但是如果我调用 context.login('some token')我再一次得到了真实。 Every succesive time after that I get true now.
之后的每一次我现在都变得真实了。 It might have to do with the fact the "console.log(userIsLoggedIn)" inside the loginHandler says "false" (the first time the context.login is called) even though the setUserLoggedIn is right above it.
这可能与 loginHandler 中的“console.log(userIsLoggedIn)”说“false”(第一次调用 context.login)有关,即使 setUserLoggedIn 就在它的正上方。 I think the userIsLoggedIn variable is changed after the context is updated in the component it's used in, but I don't know how to fix that.
我认为 userIsLoggedIn 变量在使用它的组件中更新上下文后发生了变化,但我不知道如何解决这个问题。 I will appreciate any help on this
我将不胜感激这方面的任何帮助
You cannot rely on the value of userIsLoggedIn
to have the value you passed to setUserLoggedIn
immediately.您不能依靠
userIsLoggedIn
的值来立即获得传递给setUserLoggedIn
的值。
If you want to keep track of the userIsLoggedIn
variable, you might consider something like this:如果你想跟踪
userIsLoggedIn
变量,你可以考虑这样的事情:
React.useEffect(() => {
console.log(userIsLoggedIn)
}, [userIsLoggedIn])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.