[英]React: Clean-Up function never called
I'm building a react app that uses Firebase and Firestore.我正在构建一个使用 Firebase 和 Firestore 的反应应用程序。
I'm using the onSnapshot
function so I get the real time data from Firestore, but I was wondering how I can remove that listener.我正在使用onSnapshot
function 所以我从 Firestore 获取实时数据,但我想知道如何删除该侦听器。
Yeah I know, I must use the cleanup function of the useEffect hook, but I can't make it work, here's my code:是的,我知道,我必须使用 useEffect 挂钩的清理 function ,但我无法让它工作,这是我的代码:
useEffect(() => {
let removeListener = getCanzoni(utente).onSnapshot(function (querySnapshot) {
let promises = querySnapshot.docs.map(async function (doc) {
let canzone = doc.data();
canzone.id = doc.id;
return canzone;
});
Promise.all(promises).then((canzoni) => {
cambiaCanzoni(canzoni);
});
return function cleanup() {
console.log("Removed Listener");
removeListener();
};
});
}, []);
The getCanzoni
function is imported from another files and it's definition is: getCanzoni
function 是从另一个文件导入的,它的定义是:
export function getCanzoni(utente) {
return firestore
.collection("Canzoni")
.where("utente", "==", utente.uid)
.orderBy("data", "desc");
}
When I remove the component, I don't see the 'Removed Listener' in the console.当我删除组件时,我在控制台中看不到“已删除侦听器”。 I know that the clean-up function is called when the dependency array changes or when the components is unmounted.我知道当依赖数组更改或卸载组件时会调用清理 function 。
Any idea or tips?任何想法或提示?
I've found the error:我发现了错误:
The clean up function must be defined in the hook's function body, not inside other function, like this:清理 function 必须在钩子的 function 主体中定义,而不是在其他 function 中定义,如下所示:
useEffect(() => {
let removeListener = getCanzoni(utente).onSnapshot(function (querySnapshot) {
let promises = querySnapshot.docs.map(async function (doc) {
let canzone = doc.data();
canzone.id = doc.id;
return canzone;
});
Promise.all(promises).then((canzoni) => {
cambiaCanzoni(canzoni);
});
});
return function cleanup() {
console.log("Tolto il listener");
removeListener();
};
}, []);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.