我是新手来回应原生,我很难从承诺中的firebase查询中获取值。
我尝试在promise中设置state,但控制台返回: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);
});
});
}
这是关于article的伟大的this
,它失去了它的背景。