尝试从 firebase firestore 获取数据时获取 {"_h": 0, "_i": 0, "_j": null, "_k": null}

问题描述 投票:0回答:3

我正在以 React Native 创建一个应用程序,并尝试从我的 Firestore 集合中获取一些数据。我像这样创建了这个集合:

db.collection("admin-users").add({email: "adminuseremail"})

这里

db
是一个
firebase.firestore()
对象。我正在尝试获取这样的数据:

const snapshot = db.collection("admin-users").get();
snapshot.docs.map((doc) => doc.data());

但我收到错误

TypeError: Cannot read property 'map' of undefined
。当我尝试记录快照时,我的终端中出现
{"_h": 0, "_i": 0, "_j": null, "_k": null}

这就是我的 Firebase 规则配置的样子:

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if true;
    }
  }
}

此问题可能因不正确的 Promise 处理而发生,例如不使用 async/await。我将如何在我的 React Native 应用程序中使用等待?

javascript firebase react-native google-cloud-firestore
3个回答
3
投票

get()
是一个返回
Promise
的异步操作,因此您显示的是该 Promise 的数据,而不是数据库中文档的数据。

如果您已经处于

async
上下文中,则可以使用
await
等待 Promise 完成:

const snapshot = await db.collection("admin-users").get();
snapshot.docs.map((doc) => doc.data());

如果您无法使用

await
,您始终可以使用
then
来完成相同的任务:

db.collection("admin-users").get().then((snapshot) => {
  snapshot.docs.map((doc) => doc.data());
});

处理这样的异步操作在现代 Web 开发中非常常见,因此我建议阅读以下内容:


0
投票

使用Async/Await或任何其他JS操作来处理异步操作

一般来说,

{"_h": 0, "_i": 0, "_j": null, "_k": null}
错误是由于Promise处理不正确造成的。例如,不使用 async/await。

对于您的情况,请参阅https://firebase.google.com/docs/firestore/query-data/get-data#get_a_document


0
投票

我也遇到了同样的问题。甚至使用 async/await。

我正在使用 try / catch。

感谢 Frank,我转向了 .then() 结构并且它有效。没有异步/等待!

© www.soinside.com 2019 - 2024. All rights reserved.