React Native Firebase身份验证错误处理

时间:2016-02-29 12:49:09

标签: javascript reactjs firebase react-native firebase-authentication

如何在Firebase身份验证的错误处理函数中设置状态('this.setState({})')

它在React Native中无效。

  onSignUpPress() {
    if (this.state.password !== this.state.passwordConfirmation ) {
      return this.setState({errorMessage: 'Your passwords do not match'});
    }

      ref.createUser({
        email    : this.state.email,
        password : this.state.password
      }, function(error, authData) {
        if (error) {
            console.log(error);
            // this.setState({errorMsg: error}) <-- Like this, it not work on React Native.
        } else {
            console.log("Successfully created user account with uid:", userData.uid);
        }
    });
  }
});

1 个答案:

答案 0 :(得分:3)

尝试使用es6 fat arrow语法重写函数。上述代码中肯定存在的一个问题是this未绑定到正确的范围。尝试编写如下函数:

onSignUpPress() {
    if (this.state.password !== this.state.passwordConfirmation ) {
      return this.setState({errorMessage: 'Your passwords do not match'});
    }

      ref.createUser({
        email    : this.state.email,
        password : this.state.password
      },(error, authData) => {
        if (error) {
            console.log(error);
            this.setState({errorMsg: error})
        } else {
            console.log("Successfully created user account with uid:", userData.uid);
        }
    });
  }
})