为什么我不能在超级代理请求中更新我的状态 属性?

Why can´t i update my state property in a superagent request?

我有一个按钮侦听器,它通过超级代理传递一些登录信息,我得到一个返回的令牌。现在我想将我的状态 属性 更新为接收到的令牌,我得到了正确的令牌。但是我的 this.state.token 似乎没有更新。

这是我的代码:

_btnLoginListener: function () {

    var that = this;
    superAgentRequest
        .post(URL + TOKENS_KEY)
        .type('json')
        .send({ 
            email:    this.state.usernameOrEmail,
            password: this.state.password
        })
        .end(function ( err, res ) {
            // Calling the end function will send the superAgentRequest
            if (res.status == 200) {
                /*var token = JSON.parse(res.text).token; // working*/
                /*ToastAndroid.show("POST Response -> " + token, ToastAndroid.SHORT)*/
                that.setState({
                    token: JSON.parse(res.text)
                })
                navigator.replace({
                    id:   'MainController',
                    name: 'MainController',
                });
            } else {
                notifyMessage ("Please check credentials again!")
            }
        })
  }
  notifyMessage (that.state.token)
},

您在这里处理的不是一个而是 2 个异步进程:

  1. ajax 请求已发送,其响应与您当前的代码异步运行。这意味着回调被调用你退出这个函数

  2. 之后
  3. this.setState 不会立即更改它,而是安排当前组件的状态在一段时间后更改并重新渲染。

基本意思是:您检查 this.state 太早了。