【发布时间】:2022-12-11 03:33:34
【问题描述】:
我在订阅 Firebase 的 Firestore 中的更改时遇到问题。我正在用 Firebase 开发我的第一个 React Native 项目,因此我对 Firebase 不是很熟悉。
Firebase 连接正常:我可以从 Firestore 添加和读取数据。
到目前为止,我已经尝试复制这个问题:React useState and Firebase onSnapshot 这对我不起作用。
useEffect(() => {
const q = query(collection(db, "rooms"), where("active", "==", "true"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
setUser(querySnapshot);
});
console.log("User: " + user);
return () => {
unsubscribe();
};
}, []);
当我运行它时,我得到以下输出 User: undefined
我也尝试过这种方法:
const q = query(collection(db, "rooms"), where("active", "==", "true"));
const unsubscribe = onSnapshot(q, (querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc);
});
});
unsubscribe();
那也行不通。
在这里你可以看到我的 Firestore: Firestore
我有什么想念的吗?非常感谢您的帮助!
【问题讨论】:
-
你检查过How to get data from firestore DB in outside of onSnapshot了吗?
console.log()电流甚至在onSnapshot获取数据之前就已经运行。此外,如果您在 Firestore 中将“true”存储为布尔值,则使用where("active", "==", true)而不是where("active", "==", "true"),否则查询将在其字符串所在的位置查找活动字段。 -
如果我理解正确,我需要“onSnapshot”函数来订阅更改。我不想只读取一次数据,但我想在 firestore 中获得连续的变化。
标签: reactjs firebase react-native google-cloud-firestore