试图从 Promise 中获取 firebase 值

Trying to get firebase values out of Promise

我是 React Native 的新手,我很难从 promise 中的 firebase 查询中获取值。

我尝试在 promise 中设置状态,但控制台 returns: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();
}

您在函数调用中丢失了 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 的精彩 article,但它失去了它的背景。