【发布时间】:2021-08-27 22:05:05
【问题描述】:
我的用户在他们的userData 文档中有一个名为notifications 的集合。我想实时收听这些内容,以便您可以立即看到通知(如任何社交媒体应用、facebook instagram 等)。
在我的 app.js 中,我目前有这个 useEffect:
useEffect(() => {
//this gets the user data
const unsubscribeUserData = async () => {
const userData = await getUserByUserId(currentUser.uid);
setData(userData);
};
//this subscribes to their notifications
{
/*
//This the unsub method
const unsubscribe = db
.collection("users")
.doc(currentUser.uid)
.collection("notifications")
.orderBy("date", "desc")
.onSnapshot((snapshot) => {
let tempNotifications = [];
snapshot.forEach((notification) => {
console.log("adding notification: ", notification);
tempNotifications.push(notification.data());
});
setNotifications(tempNotifications);
});
*/
}
//What do I do with useRef?
const unsubscribe = useRef();
if (currentUser) {
//If there is an auth object stored in my auth context, get their data and subscribe to their notifications
unsubscribeUserData();
unsubscribe();
} else {
//If there isn't, unsub from the notifications and set data to null
setData(null);
unsubscribe();
}
return () => {
//If they have closed the webpage, unubscribe
unsubscribe();
};
}, [currentUser]);
谁能给我一个关于如何构建它以便在需要时成功取消订阅的提示?
谢谢!
编辑(我相信这可行!)
useEffect(() => {
const getUserData = async () => {
const userData = await getUserByUserId(currentUser.uid);
setData(userData);
};
if (currentUser) {
getUserData();
return (unsubscribeRef.current = db
.collection("users")
.doc(currentUser.uid)
.collection("notifications")
.orderBy("date", "desc")
.onSnapshot((snapshot) => {
let tempNotifications = [];
snapshot.forEach((notification) => {
console.log("adding notification: ", notification);
tempNotifications.push(notification.data());
});
setNotifications(tempNotifications);
}));
} else {
setData(null);
}
}, [currentUser]);
我相信在实际快照侦听器处调用 return 与调用 cleanup return 相同,但是在这里执行此操作会跳过 not a function 错误
【问题讨论】:
-
useEffect钩子回调不能是async。我不知道这是否是您的问题的原因,但它肯定对您没有帮助。 -
感谢您的回复,啊,我明白了,很奇怪。如何等待 getUserbyUserId() 的结果? @DrewReese
-
您需要获取整个回调并在同步挂钩回调中定义它,然后调用它。不过这里的问题是你仍然需要从钩子回调中返回一个清理函数来取消订阅。我会尝试使用 React ref 来保存对取消订阅函数的引用,以便在清理函数中调用。
-
@DrewReese 好的,太棒了,谢谢,我看看,你是说 useRef 钩子吗?
-
肯定,
createRef对于功能组件的工作方式并不完全相同。
标签: reactjs firebase google-cloud-firestore react-hooks use-effect