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

使用Firebase展示帖子时出现module.db.collection is not a function错误

使用Firebase展示帖子时出现module.db.collection is not a function错误

嘿,我一眼就看出问题啦——你在混用Firebase不同版本的API写法!你的firebase.js已经用了最新的v9+模块化SDK(用getFirestore初始化数据库),但Feed.js里还在沿用v8的旧写法(db.collection()),甚至还导入了compat兼容包,这就导致了冲突,才会出现这个错误。

别担心,我给你一步步改过来:

第一步:清理Feed.js里的兼容包导入

把Feed.js里这些旧的compat导入删掉:

import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';

换成v9+的必要导入:

import { collection, onSnapshot, addDoc, serverTimestamp } from "firebase/firestore";

第二步:修改Firestore操作代码

原来的db.collection()写法在v9+里要换成collection(db, "集合名")的形式,具体改法如下:

1. 监听posts集合的快照(useEffect部分)

把原来的代码:

useEffect(() => {
    db.collection("posts").onSnapshot(snapshot => (
        setPosts(snapshot.docs.map((doc) => (
            {
                id: doc.id,
                data: doc.data(),
            }
        )))
    ));
}, []);

改成:

useEffect(() => {
    const unsubscribe = onSnapshot(collection(db, "posts"), (snapshot) => {
        setPosts(snapshot.docs.map(doc => ({
            id: doc.id,
            data: doc.data()
        })));
    });
    // 组件卸载时取消监听,避免内存泄漏
    return () => unsubscribe();
}, []);

2. 发送帖子的sendPost函数

把原来的:

const sendPost = e => {
    e.preventDefault();

    db.collection("posts").add({
        name: "Luke Knight",
        description: "this is a test",
        message: input,
        photoUrl: "",
        timestamp: firebase.firestore.FieldValue.serverTimestamp(),
    });
};

改成:

const sendPost = async (e) => {
    e.preventDefault();
    
    try {
        await addDoc(collection(db, "posts"), {
            name: "Luke Knight",
            description: "this is a test",
            message: input,
            photoUrl: "",
            timestamp: serverTimestamp()
        });
        // 发送成功后清空输入框
        setInput("");
    } catch (err) {
        console.error("添加帖子失败:", err);
    }
};

最后检查一下

确保你的firebase.js里的导出是正确的,现在这样就没问题:

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

const firebaseConfig = {
    // 你的配置信息
};

const firebaseApp = initializeApp(firebaseConfig);
const db = getFirestore(firebaseApp);
const auth = getAuth();

export { db, auth };

这样修改后,应该就能正常获取和发布帖子啦,不会再出现那个错误了。

备注:内容来源于stack exchange,提问作者Luke

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 18:14:31