我是 React Native 和 JavaScript 的新手。我来自 java 和 android 开发。 我希望在 const 中调用函数,但无论我尝试什么方式,我都会遇到很多错误。
我收到错误:
this.collectionUpdate is not a function
主屏幕:
onCollectionUpdate = (doc) => {
const items = [];
doc.forEach((doc)=> {
console.log("doc received");
const {Name, imageDownloadUrl,Location} = doc.data();
items.push({
key: doc.id,
doc, //DocumentSnapshot
Name,
imageDownloadUrl,
Location,
});
});
this.setState({
items,
loading: false,
});
}
componentDidMount() {
const geoQuery = geoFirestore.query({
center: new firebase.firestore.GeoPoint(10.38, 2.41),
radius: 10.5
});
const onReadyRegistration = geoQuery.on('ready', () => {
console.log('GeoFirestoreQuery has loaded and fired all other events for initial data');
});
const onKeyEnteredRegistration = geoQuery.on('key_entered', function(key, doc, distance) {
console.log(key + ' entered query at ' + doc.coordinates.latitude
+ ',' + doc.Name
+ ',' + doc.coordinates.longitude
+ ' (' + distance + ' km from center)')
this.onCollectionUpdate(doc)
});
this.onCollectionUpdate = this.onCollectionUpdate.bind(this);
}
我知道这可能对我不起作用,因为我对 javascript 的了解不够,无法理解我做错了什么,但是,我很快就会开始学习 Javascript 类(class),以便更好地理解。但我会非常感谢任何能够告诉我哪里出错了的人。我觉得这是因为我试图在 const 中调用函数?
最佳答案
这与const
无关,而是与函数
有关。使用关键字function
编写的函数为this
创建一个新的作用域。当您在函数
内部使用this
时,您看到的是与其外部不同的this
。
geoQuery.on('key_entered', function(key, doc, distance) {
this.onCollectionUpdate(doc) // wrong "this"
})
解决这个问题的一个简单方法是在此处使用 =>
函数:
geoQuery.on('key_entered', (key, doc, distance) => {
this.onCollectionUpdate(doc) // correct "this"
})
关于javascript - 在 const javascript React Native 中调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52542241/