【问题标题】:Firebase Reactjs - ae.collection is not a functionFirebase Reactjs - ae.collection 不是函数
【发布时间】:2021-12-01 22:02:58
【问题描述】:

我无法弄清楚这里的错误是什么。我制作了教程 Firebase/website,并在我的项目中做了同样的事情。我试图在我的 React 网站上打印出我在 Firebase 上创建的集合,但在 db.collection 行出现错误:Uncaught (in promise) TypeError: ae.collection is not a function

component.js:

// React
import { useState, useEffect } from "react";
import { db, collection, getDocs  } from '../../../firebase.js';

const [holder, setHolder] = useState([]); // update
  
  db.collection("holder").onSnapshot((snapshot) => {
    setHolder(
      snapshot.docs.map((doc) => ({
        id: doc.id,
        data: doc.data(),
      }))
    );
  });
  console.log({ holder });

更新:firebase.js 下面

    // Import the functions you need from the SDKs you need
    import { initializeApp } from "firebase/app";
    import { getAnalytics } from "firebase/analytics";
    import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
    // TODO: Add SDKs for Firebase products that you want to use
    // https://firebase.google.com/docs/web/setup#available-libraries
    
    // Your web app's Firebase configuration
    // For Firebase JS SDK v7.20.0 and later, measurementId is optional
    const firebaseConfig = {
...
    };
    
    // Initialize Firebase
    const app = initializeApp(firebaseConfig);
    const analytics = getAnalytics(app);
    
    export const db = getFirestore(app);

谢谢!

【问题讨论】:

标签: javascript reactjs firebase google-cloud-firestore


【解决方案1】:

您正在使用具有全新语法的 Firebase Modular SDK,您必须在代码中使用相同的语法。尝试将代码重构为:

// React
import { useState, useEffect } from "react";
import { db } from '../../../firebase.js';
import { onSnapshot, collection } from 'firebase/firestore'

const [holder, setHolder] = useState([]); // update
 
onSnapshot(collection(db, 'holder'), (snapshot) => {
  setHolder(
    snapshot.docs.map((doc) => ({
      id: doc.id,
      data: doc.data(),
    }))
  );
})

还要确保您的getFirestore 导入来自firebase/firestore,而不是来自firebase.js 中的lite,否则您将遇到this issue

import { getFirestore } from 'firebase/firestore';

【讨论】:

  • 嗨!你能给我推荐一个页面,他们解释如何使用新的 Modular sdk 访问数据?
  • 以一个集合的所有文档为例
  • @Hurinj 是的,您可以查看documentation 关于获取多个文档的信息。
  • 谢谢,有什么方法可以在没有查询的情况下完成,只需获取集合中的所有文档?
猜你喜欢
  • 2021-06-11
  • 2020-12-11
  • 2015-10-29
  • 2021-12-05
  • 2020-04-05
  • 2021-11-02
  • 2020-04-23
  • 2020-12-12
  • 1970-01-01
相关资源
最近更新 更多