【问题标题】:I can't figure out how to work with the object returned by Firebase get query我不知道如何使用 Firebase 获取查询返回的对象
【发布时间】:2021-12-31 20:50:35
【问题描述】:

我正在使用 Expo 构建一个 React Native 应用程序并集成 Firebase(实时数据库),我知道这有一些限制 (https://docs.expo.dev/guides/using-firebase/)。我正在尝试使用await get(query(... 获取数据的快照并已成功完成,但我无法弄清楚我正在使用什么。当我console.log 它时,我得到了这个:

Object {
  "key1": value1,
  "key2": value2,
}

我试图使用 Object.keys() 返回一个键数组,但它返回了这个:

Array [
  "_node",
  "ref",
  "_index",
]

这与我在 Internet 上看到的 Object.keys() 的示例不符,这让我认为这不是我认为的 JSON 对象。我试过用其他一些东西到处乱摸,但无法弄清楚。问题是,当我在对象上使用 typeof 时,它只是返回“对象”,这对我来说有点太模糊了,无法带到谷歌机器上。

以下是我的代码的表示。感谢您的帮助。

import { initializeApp } from 'firebase/app';
import { get, getDatabase, query, ref } from 'firebase/database';

const firebaseConfig = {
    databaseURL: '<myURL>',
    projectId: '<myID>',
};
const app = initializeApp(firebaseConfig);

export default async function myFunction() {
    const db = getDatabase(app);
    const readReference = ref(db, '/<I am only reading a piece of the data>')
    const existingData = await get(query(readReference))
    const dataKeys = Object.keys(existingData)
    console.log(dataKeys)
    console.log(existingData)
    console.log(typeof existingData)
}

【问题讨论】:

    标签: javascript react-native firebase-realtime-database expo


    【解决方案1】:

    您从 Firebase 返回的内容称为 DataSnapshot,其中包含您读取的位置的 JSON 以及更多元数据。

    如果您只想获取快照的 JSON 值,请使用 snapshot.val(),如 Storing Data and Receiving Updates 的 Expo 文档中所示。

    类似:

    const existingData = await get(query(readReference))
    const dataKeys = Object.keys(existingData.val())
    console.log(dataKeys)
    console.log(existingData.val())
    console.log(typeof existingData.val())
    

    【讨论】:

    • 非常感谢,弗兰克。我只是不了解 DataSnapshot 层。这解决了问题,现在我知道了,我会去了解更多。
    猜你喜欢
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2021-06-15
    相关资源
    最近更新 更多