You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React.js调用Firebase报错db.collection is not a function求助

问题:Uncaught TypeError: db.collection is not a function 解决方法

问题描述

在React组件中点击按钮从Firestore获取数据时,抛出错误:Uncaught TypeError: db.collection is not a function,相关代码如下:

组件代码(FetchedData.jsx)

import { useState, useEffect } from "react";
import { db } from "../../firebase";

const Fetch = () => {
  const [allDocs, setAllDocs] = useState([]);
  const [singleDoc, setSingleDoc] = useState({});

  const fetchAll = (e) => {
    db.collection("f_Collections")
      .get()
      .then((snapshot) => {
        if (snapshot.docs.length > 0) {
          snapshot.docs.forEach((doc) => {
            setAllDocs((prev) => {
              return [...prev, doc.data()];
            });
          });
        }
      });
    console.log(allDocs);
  };

   return (
    <div className="">
      qwerty
      <button type="button" onClick={fetchAll} className="">
        Fetch
      </button>
    </div>
  );
};

export default Fetch;

Firebase配置文件

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import "firebase/firestore";
import * as firebase from "firebase/app";

const firebaseConfig = {
  apiKey: "-",
  authDomain: "give-authorization.firebaseapp.com",
  projectId: "give-authorization",
  storageBucket: "give-authorization.appspot.com",
  messagingSenderId: "-",
  appId: "-"
};

const foundationsConfig = {
  apiKey: "-",
  authDomain: "give-foundationsorganization.firebaseapp.com",
  projectId: "give-foundationsorganization",
  storageBucket: "give-foundationsorganization.appspot.com",
  messagingSenderId: "-",
  databaseURL: "",
  appId: "-"
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);

const foundationsApp = initializeApp(foundationsConfig, "foundations");
export const db = getFirestore(foundationsApp);

原因分析

你使用的是Firebase v9+ 模块化SDK,但组件代码里依然沿用了v8及更早版本的命名空间语法(db.collection())。v9+的模块化SDK中,Firestore的操作不再通过实例方法调用,而是需要导入对应的独立函数来完成。

解决方法

修改组件代码,适配Firebase v9+的模块化语法:

  1. 从firebase/firestore导入collection和getDocs函数
  2. 替换原有的db.collection().get()逻辑为模块化调用方式
  3. 优化数据更新逻辑(避免多次调用setAllDocs,先收集所有数据再一次性更新)

修改后的组件代码:

import { useState } from "react";
import { db } from "../../firebase";
// 导入v9+需要的Firestore函数
import { collection, getDocs } from "firebase/firestore";

const Fetch = () => {
  const [allDocs, setAllDocs] = useState([]);
  const [singleDoc, setSingleDoc] = useState({});

  const fetchAll = async (e) => {
    try {
      // 获取集合引用
      const colRef = collection(db, "f_Collections");
      // 获取集合快照
      const snapshot = await getDocs(colRef);
      
      if (snapshot.docs.length > 0) {
        // 一次性提取所有文档数据
        const docsData = snapshot.docs.map(doc => doc.data());
        // 更新状态
        setAllDocs(docsData);
      }
      console.log(allDocs);
    } catch (err) {
      console.error("获取数据失败:", err);
    }
  };

   return (
    <div className="">
      qwerty
      <button type="button" onClick={fetchAll} className="">
        Fetch
      </button>
    </div>
  );
};

export default Fetch;

另外,Firebase配置文件里的import "firebase/firestore";和import * as firebase from "firebase/app";属于v8的冗余代码,可以删除,简化后的配置文件:

import { initializeApp } from "firebase/app";
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey: "-",
  authDomain: "give-authorization.firebaseapp.com",
  projectId: "give-authorization",
  storageBucket: "give-authorization.appspot.com",
  messagingSenderId: "-",
  appId: "-"
};

const foundationsConfig = {
  apiKey: "-",
  authDomain: "give-foundationsorganization.firebaseapp.com",
  projectId: "give-foundationsorganization",
  storageBucket: "give-foundationsorganization.appspot.com",
  messagingSenderId: "-",
  databaseURL: "",
  appId: "-"
};
const app = initializeApp(firebaseConfig);
export const auth = getAuth(app);

const foundationsApp = initializeApp(foundationsConfig, "foundations");
export const db = getFirestore(foundationsApp);

内容的提问来源于stack exchange,提问作者Krzysztof_P

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 09:23:41