React-native Firebase Auth setState в onAuthStateChanged получил TypeError: this.setState не является функцией - PullRequest
0 голосов
/ 02 июля 2019

Я начинаю с response-native и пытаюсь получить пользовательские данные firebase с помощью onAuthStateChanged.

Я пытался сделать bind this, но до сих пор понятия не имею об этом.

это мой конструктор

constructor(props) {
    super(props);
    this.state = {
    isUid: '',
      isProvider:'',

      isPhoneNumber:'', 
    };

и это мой onAuthStateChange в componentDidMount

componentDidMount() { 
var user = firebase.auth().currentUser;
firebase.auth().onAuthStateChanged(function (user) {
    if (user) {
      user.providerData.forEach(function (profile) {

        this.setState({isProvider: profile.providerId}, console.log(isProvider)).bind(this); 
        this.setState({isPhoneNumber: profile.phoneNumber}, console.log(isPhoneNumber)).bind(this);
        this.setState({isUid: user.uid}, console.log(isUid)).bind(this);
});
} else {
  console.log('no user');
}
}

1 Ответ

0 голосов
/ 02 июля 2019

Поскольку вы находитесь в обратном вызове onAuthStateChanged, значение this отличается от этого.

Самое простое решение - использовать жирную стрелку, которая поддерживает значение this:

firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      user.providerData.forEach(function (profile) {
        this.setState({isProvider: profile.providerId}, console.log(isProvider)).bind(this); 
        this.setState({isPhoneNumber: profile.phoneNumber}, console.log(isPhoneNumber)).bind(this);
        this.setState({isUid: user.uid}, console.log(isUid)).bind(this);
      });
    } else {
      console.log('no user');
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...