开发者问题收集

React Native Firebase 身份验证错误处理

2016-02-29
1334

如何在 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个回答

尝试使用 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);
        }
    });
  }
})
Nader Dabit
2016-02-29