簡體   English   中英

const javascript內的調用函數反應本機

[英]Call Function within const javascript react native

我是新來的響應本機和JavaScript的人。 我來自java和android dev。 我希望在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進行課程,以獲得更好的理解。 但是對於任何可以向我展示我要去哪里的人,我都會非常感激。 我感覺是因為我試圖在const中調用函數?

這與const無關,而與function 用關鍵字function編寫的function this創建了新范圍。 當您使用this一內部function ,你正在尋找一個不同的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"
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM