Попытка получить значения Firebase из Promise - PullRequest
1 голос
/ 09 марта 2019

Я новичок, чтобы реагировать на родную систему, и мне трудно получать значения из запроса Firebase внутри обещания.

Я пытался установить setState в обещании, но консоль возвращает: TypeError: _this2.setState не является функцией.

_getActivites() {
      const latitude = 42.297761;
      const longitude = 4.636235;
      const radius = 5;

  var keys = [];
  var activitesToState = [];

  const firebaseRef = firebase.database().ref("activites_locations/");
  const geoFire = new GeoFire(firebaseRef);
  var geoQuery;
  var activites = [];

  geoQuery = geoFire.query({
    center: [latitude, longitude],
    radius: radius
  });

  geoQuery.on("key_entered", function(key, location, distance) {
    keys.push(key);
  });

  geoQuery.on("ready", function() {
    var promises = keys.map(function(key) {
      return firebaseRef.child(key).once("value");
    });
    Promise.all(promises).then((snapshots) => {
      snapshots.forEach(function(snapshot) {
        activites.push(snapshot.val());
      });
      this.setState({
        activitesState: activites,
      })
    }).catch((error) => {
      console.log(error);
    });

  });

};

componentDidMount() {
  firebase.auth().signInAnonymously()
    .then(() => {
      this.setState({
        isAuthenticated: true,
      });
  });

  this._getActivites();
}

1 Ответ

0 голосов
/ 09 марта 2019

Вы теряете значение this в вызовах функций.Вы должны связывать свои вызовы, обновляя свои функции до функций стрелок.Вы также можете остановить предотвращение потери this, установив его в качестве переменной в области действия вашей функции.

Рефакторинг вашего кода может привести к следующему:

_getActivites = () => { // change to arrow function
  const that = this;  // capture the value of this
  const latitude = 42.297761;
  const longitude = 4.636235;
  const radius = 5;

  var keys = [];
  var activitesToState = [];

  const firebaseRef = firebase.database().ref('activites_locations/');
  const geoFire = new GeoFire(firebaseRef);
  var geoQuery;
  var activites = [];

  geoQuery = geoFire.query({
    center: [latitude, longitude],
    radius: radius
  });

  geoQuery.on('key_entered', (key, location, distance) => { // change to arrow function
    keys.push(key);
  });

  geoQuery.on('ready', () => { // change to arrow function
    var promises = keys.map((key) => { // change to arrow function
      return firebaseRef.child(key).once('value');
    });
    Promise.all(promises).then((snapshots) => {
      snapshots.forEach((snapshot) => {
        activites.push(snapshot.val());
      });
      that.setState({ activitesState: activites }); // use "that" instead of "this"
    }).catch((error) => {
      console.log(error);
    });
  });
}

Здесьэто отличная статья о this и она теряет свой контекст.

...