试图从Promise中获得Firebase的价值

时间:2019-03-09 09:56:51

标签: firebase react-native geofire

我是新来的响应本机的人,我很难在promise中从Firebase查询中获取值。

我试图在promise中设置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 :(得分:0)

您在函数调用中丢失了this的值。您应该通过将函数更新为箭头函数来绑定您的调用。您还可以通过将this设置为函数范围内的变量来阻止丢失。{p>

重构代码,您可能会遇到类似这样的事情:

_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的{​​{3}}很棒,而且它失去了上下文。