如何在React-Native中退订Firestore侦听器?

时间:2020-04-20 15:31:57

标签: javascript firebase react-native google-cloud-firestore

如何在React-Native中退订Firestore侦听器?我有一个可以在Firestore中获取和收听更改的函数:

_fetchPatientsList() {
        var query = firestore().collection('Collection').doc().collection('public');
        query = query.where('act', '==', 1);
        query = query.where('city', '==', this.state.selected_city);
        query = query.orderBy('update_time', 'desc');
        query = query.limit(10);

        query.onSnapshot({
            error: (e) => this.setState({ errorMessage: e, refreshingPatients: false }),
            next: (querySnapshot) => {
                ///do something      
            },
        });
 }

我想注销时退订:

    _logOutHandler = () => {
    auth()
        .signOut()
        .then(() => {
            console.log('User signed out!')
        });
    let unsub = firestore().collection('Collection').doc().collection('public').onSnapshot(() => {
    });

    // Stop listening for changes
    unsub();
}

这是正确的方法吗?

1 个答案:

答案 0 :(得分:0)

您必须保存一个侦听器引用const unsubRef = query.onSnapshot

使用参考,例如:

const unsubRef = query.onSnapshot({
 error: (e) => this.setState({ errorMessage: e, refreshingPatients: false }),
 next: (querySnapshot) => {
   ///do something      
 },
});

//just make it to unsubscribe
unsubRef();

要停止其他功能的监听器,您可以这样做:


import from ....

//variables
let unsubRef;


// function to stop listener
stopListener = (unsubRef) => {
   unsubRef();
};

//save the reference for this query
unsubRef = query.onSnapshot({
            error: (e) => this.setState({ errorMessage: e, refreshingPatients: false }),
            next: (querySnapshot) => {
                ///do something      
            },
        });


//other function you want cancel listener
otherFunc = async() => {
   // some code

   //stop the listener
   await this.stopListener(unsubRef);
   //signout code
};

您可以在此处查看更多详细信息: https://rnfirebase.io/firestore/usage#realtime-changes 要么 https://firebase.google.com/docs/firestore/query-data/listen#detach_a_listener