首页 > 解决方案 > 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)
}

标签: javascriptreactjs

解决方案


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')


推荐阅读