Javascript 在if语句中声明全局变量并更改其值

Javascript 在if语句中声明全局变量并更改其值,javascript,reactjs,Javascript,Reactjs,嗨,我正在使用react开发一个应用程序。我想检查我的用户是否已经存在 这是我检查用户是否存在的方法 var userExists=false getProfile((err, profile) => { var userId=profile.sub.substring(6,profile.sub.length) console.log(userId) axios.get('http://localhost:9000/user/'+userId) .th

嗨,我正在使用react开发一个应用程序。我想检查我的用户是否已经存在

这是我检查用户是否存在的方法

var userExists=false 

getProfile((err, profile) => {
    var userId=profile.sub.substring(6,profile.sub.length)
    console.log(userId)
    axios.get('http://localhost:9000/user/'+userId)
    .then(response =>{
      console.log(userId)
        console.log("getting",response.data) 
        if (response.data.id==userId){
          userExist=true
           console.log(userExist)
        }
        else{
          console.log(response.data)
          console.log()

        }
    })  

}) 

console.log(userExist) 
它总是在最后显示false(在if测试之外)。
我的问题是:在应用更改时(即使在if-else测试中),如何定义全局变量并更改其值?

使用可以使用
窗口
对象

例如:

window.userExists=false
foo()=>{
   window.userExists=true
}
foo()

使用redux和redux-thunk。用户信息可能是应用程序/组件状态的一部分。没有其他解决方案?当然,但我不明白您为什么选择其他解决方案。您如何管理应用程序状态?您是否正在使用setState编写状态完整的组件?不,它是无状态组件。这与redux完全无关。问题是,axios请求是异步的。因此,当您记录全局变量时,请求尚未完成,将
userExists
保留在其初始状态,即
false
。您需要处理基于回调的请求。这与redux无关。它甚至与react无关。