我目前正在使用 React Native Expo 构建我的应用程序。在我的应用程序中,我必须将用户的条目保存到数据库中。由于我的用户可能没有稳定的互联网连接,因此我一直在寻找一种可以立即处理离线场景的数据库服务。 firebase 的 Firestore 是自然而然的选择。请阅读此处 firestore 离线模式 的工作原理。
所以我继续在我的应用程序中实现了 firestore,一切都按预期工作。但在离线模式下,firestore确实显示了任何数据。它也不会抛出任何错误。
这是我非常简单的 Firestore 设置
import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";
import { firebaseConfig } from "./config";
const app = initializeApp(firebaseConfig);
export const db = getFirestore(app);
这是我从 firestore 获取数据的方法
import { db } from "../index";
import {
collection,
doc,
getDoc,
QueryDocumentSnapshot,
} from "firebase/firestore";
export const firestoreService = {
get: async <T>(collectionName: string, id: string): Promise<T | null> => {
const docSnap = await getDoc(doc(db, collectionName, id));
return docSnap.exists() ? (docSnap.data() as T) : null;
},
}
当互联网连接可用时,此代码工作得很好,但一旦设备进入离线模式,它就会给出空对象。
根据官方文档,当涉及 android 或 ios 应用程序时,firestore 应在离线模式下工作,无需任何额外的代码更改。但它在我的博览会应用程序中不起作用。 我尝试了各种选项,例如
getDocsFromCache()
方法,希望它至少能返回缓存的数据,然后我可以手动处理离线场景。但没有成功。
getAll: async <T>(collectionName: string): Promise<T[]> => {
const querySnapshot = await getDocsFromCache(collection(db, collectionName));
return querySnapshot.docs.map(
(doc) => ({ id: doc.id, ...doc.data() } as T)
);
},
如何使其在离线模式下工作?
您使用的是 Firebase 的 Web SDK,默认情况下未启用离线缓存(请参阅配置离线持久性上的文档)。该部分还包含有关如何在 Web SDK 中启用离线持久性的代码。