传递承诺的结果

时间:2017-03-14 14:23:57

标签: javascript reactjs firebase promise firebase-authentication

所以在我的反应代码中我有这个:

  componentDidMount = () => {
    firebase.auth().getRedirectResult().then(function(result) {
        if (result.credential) {
          var token = result.credential.accessToken;
        }
        var ruser = result.user;
        console.log(ruser.displayName, 'lol'); //THIS LOGS CORRECTLY
      }).catch(function(error) {
        var errorCode = error.code;
        var errorMessage = error.message;
        var email = error.email;
        var credential = error.credential;
      }).then(function(result){
        this.setState({user: ruser});
        console.log(result, 'rslt'); //THIS LOGS UNDEFINED 
      });

  }

我基本上想要设置登录用户的状态。但是,当我传递这个时,我得到了未定义,我对promises做了什么错误?我想传递结果并使其在函数范围之外可用...

1 个答案:

答案 0 :(得分:0)

承诺中的声明是没有意义的,除非你返回你声明的内容 - 如果你想传递它,你必须返回result

componentDidMount = () => {
  firebase.auth().getRedirectResult().then(function(result) {
      if (result.credential) {
        var token = result.credential.accessToken;
      }

      console.log(result.user.displayName, 'displayName');

      return result; // this will be passed down
    }).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;
      var email = error.email;
      var credential = error.credential;
    }).then(result => {
      this.setState({user: result.user});

      console.log(result.user, 'user'); 
    });
}

另外 - 正如nils所提到的,你必须在上一个.then中使用arrow function来使用父亲的上下文及其setState