React 原生 Firebase 身份验证错误处理

React Native Firebase authentication error handling

本文关键字:错误 处理 身份验证 Firebase 原生 React      更新时间:2023-09-26

如何在 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);
        }
    });
  }
});

尝试使用 es6 胖箭头语法重写函数。上面的代码中肯定的一个问题是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);
        }
    });
  }
})