【问题标题】:Get Firebase Collection into simple array将 Firebase 集合放入简单的数组中
【发布时间】:2021-12-10 14:50:16
【问题描述】:

我正在尝试将 Firebase 中集合中的所有项目反应到一个数组中,以便稍后在 React 中使用。

我目前有这个:

  const retrievegear = firebase.firestore().collection('gear').get().then(querySnapshot => {
    querySnapshot.forEach(doc => {
      const check = doc.data().Name;
        console.log(check);
    });
  });

这很好 - 它显示了装备集合中所有物品的名称。但我希望它在一个数组中,并且只想要集合中的一些字段。

然后我使用这个数组来填充复选框 - 所以我需要在某处声明 const 以便我的 return 可以访问它。

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore


    【解决方案1】:

    Firestore get() 方法是异步的,并返回一个 Promise,因此只有在传递给 then() 的回调函数中才能得到它的结果。

    因此,您需要执行以下操作:

    const myArray = [];
    firebase.firestore().collection('gear').get().then(querySnapshot => {
        querySnapshot.forEach(doc => {
          const check = doc.data().Name;
            console.log(check);
            myArray.push(check);
        });
        // Here do whatever you want with the myArray array which contains the data from the collection
    
      });
    

    如果您想将此代码转换为可以从代码中其他位置调用的函数,请执行以下操作(我们使用 async/await 以提高可读性):

    async function getGearData() {
        const myArray = [];
        const querySnapshot = await firebase.firestore().collection('gear').get();
        querySnapshot.forEach(doc => {
            const check = doc.data().Name;
            console.log(check);
            myArray.push(check);
        });
        return myArray;
    }
    

    注意这个函数是异步的,所以需要如下调用:

    getGearData()
    .then(gearData => {
      // Here and only here you get the value 
      console.log(gearData);
      // ....
    })
    

    请注意,您还可以对querySnapshot.docs 返回的数组使用map() 方法。

    【讨论】:

    • 好的,谢谢 - 但是我如何将这个 myArray 加载到我以后可以使用的常量中?
    • 查看更新。无论如何,您都需要处理异步方面。
    猜你喜欢
    • 1970-01-01
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 2018-03-16
    • 2018-08-24
    • 1970-01-01
    • 2012-08-28
    • 1970-01-01
    相关资源
    最近更新 更多