javascript - ReactJS -> Why does my state return undefined on the first try?
问题描述
I am trying to save the loginState of a user in a state and then send it to a cookie. The thing is that the first time I log in through my login form I set the loginState to 'logged in', then I console log it but it returns undefined and then on the second press of the button login(after I've already logged in successfully) it finally says 'logged in' in the console. Why is that? How do I fix it? Here's the relevant code:
const [loginStatus, setLoginStatus]= useState()
//Here we have irrelevant code that validates the login info entered and then it calls authorizeUser
const authorizeUser=()=>{
setLoginStatus('logged in')
console.log(loginStatus)
}
解决方案
useEffect
runs after every render, so even if you're setting the value of loginStatus
in useEffect()
, on the first render loginStatus
will have no value. You can set a default value before the first render by passing a default value in your call to useState()
, like this:
const [loginStatus, setLoginStatus] = useState('whatever you want here, even a null string')
推荐阅读
- python - sympy lambdify 与元组中的函数参数?
- android - 默认情况下,AWS Pinpoint 在 react native 中选择退出 Android 用户的推送通知
- c++ - 如何检查升压融合序列是否是适应结构?
- react-native - 如何在 package.json 中包含 *forked* github 分支作为依赖项
- html - 如何使用文件应用在 iPhone 上查看结束编辑 html 文件?
- java - 如何解析邮递员收藏?
- docker - 如何在 docker 镜像中安装 @vue/cli
- c# - IntPtr.operator + (IntPtr, int) 不能调用 operator 或 accessor
- python - Beautifulsoup - 如何从's获取文本
- php - PHP Array POST UPDATE 只影响最后一行