如何从函数组件中的另一个函数调用Firestore取消订阅函数



我有以下函数,它在单击时运行。它基本上启动了一个Firestore侦听器来获取消息。它还声明了一个取消订阅函数,我正试图从另一个函数调用它:

const getMessages = (uid) => {
const ref = firebase.firestore().collection('Chats').doc(uid).collection('Messages');
const query = ref.where("uid", "==", uid).orderBy('timestamp', 'desc').limit(25);  

const unsubFromMessages = query.onSnapshot((snapshot) => {
if (snapshot.empty) {
console.log('No matching documents.');                                

}

snapshot.docChanges().forEach((change) => {


if (change.type === 'removed') {

console.log(change.doc.data().content)

} else if (change.type === 'added') {                


setMessages(prevFiles => ([...prevFiles, {
id: change.doc.id, body: change.doc.data()
}]))                          

// setTimeout( this.scrollToBottom(), 2000)

}


});
}, (error) => {console.log(error)});             
}

正如你在里面看到的,我声明了一个函数来取消订阅Firestore侦听器(const unsubFromMessages=query.onSnapshot(;unsobFromMessages";从基本上关闭聊天的另一个功能点击另一个按钮时的功能。

这是关闭聊天功能:

const closeChat = () => {    
setMessages([]);
unsubFromMessages();        
}

不幸的是,closeChat函数无法访问unsobFromMessages函数来取消订阅Firestore侦听器。我得到以下错误:

Line 177:5:  'unsubFromMessages' is not defined  no-undef

我知道如何在类组件中做到这一点,我只需将函数声明为this.unsubFromMessages=。。。然后从任何其他函数调用它,但我不知道如何在函数组件中执行。请告知。

您可以将unsubFromMessages回调存储在React ref中,并在另一个点击手中访问它。

const unsubFromMessagesRef = React.useRef();
...
const getMessages = (uid) => {
...
const unsubFromMessages = query.onSnapshot((snapshot) => { ..... };
unsubFromMessagesRef.current = unsubFromMessages;
...
}
...
const closeChat = () => {    
setMessages([]);
unsubFromMessagesRef.current && unsubFromMessagesRef.current();        
}

组件卸载时不要忘记取消订阅:

useEffect(() => {
return () => {
unsubFromMessagesRef.current && unsubFromMessagesRef.current()
};
}, []);

最新更新