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

React项目使用Firebase 9调用Firestore出现编译错误如何解决?

Firebase 9.5.0 React项目Firestore数据拉取修复方案

问题核心原因

  • Firebase 9 采用模块化API,不再支持v8及更早版本的firebase.firestore()命名空间调用
  • 组件内未声明缺失的状态变量,且使用了已废弃的旧版Firestore语法
  • return语句中使用了未定义的变量

第一步:修复firebase.js配置文件

修改后的完整代码如下:

import { initializeApp } from 'firebase/app';
// 导入Firebase 9提供的Firestore初始化方法
import { getFirestore } from 'firebase/firestore'

const firebaseConfig = {
  apiKey: "(替换为你的apiKey)",
  authDomain: "reactcoder-17fc7.firebaseapp.com",
  projectId: "reactcoder-17fc7",
  storageBucket: "reactcoder-17fc7.appspot.com",
  messagingSenderId: "588405796332",
  appId: "(替换为你的appId)",
  measurementId: "(可选,填写你的measurementId)"
};

const app = initializeApp(firebaseConfig);
// 初始化Firestore实例
const db = getFirestore(app)

export function getFirebase() {
    return app
}

export function getFirestore() {
    return db
}

第二步:修复ItemListContainer组件

修改后的完整代码如下:

import ItemList from "./ItemList";
import { useState, useEffect } from "react";
// 导入Firebase 9 Firestore相关操作方法
import { collection, getDocs } from "firebase/firestore"
import { getFirestore } from "../Firebase/firebase"

const ItemListContainer = () => {
    // 声明所需状态变量,解决setLoading、setItems未定义的报错
    const [data, setData] = useState([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        const fetchProducts = async () => {
            setLoading(true);
            const db = getFirestore();
            // 获取Products集合引用
            const productsCollection = collection(db, "Products");
            try {
                // 拉取集合下所有文档
                const querySnapshot = await getDocs(productsCollection);
                if(querySnapshot.empty) {
                    console.log("未查询到产品数据");
                    return;
                }
                // 格式化数据,携带文档id避免渲染key缺失问题
                const productsList = querySnapshot.docs.map(doc => ({
                    id: doc.id,
                    ...doc.data()
                }));
                setData(productsList);
            } catch (error) {
                console.log("拉取产品数据失败:", error);
            } finally {
                setLoading(false);
            }
        }
        fetchProducts();
    }, [])

    // 加载状态展示,可根据需求自定义样式
    if(loading) return <div>产品加载中...</div>

    return (
        <>
            <ItemList items={data} />
        </> 
    )
}

export default ItemListContainer

额外验证说明

如果修改后仍拉取不到数据,请检查以下两项:

  • Firestore控制台的集合名称是否为Products(大小写完全匹配),集合下是否有已写入的文档数据
  • Firestore安全规则是否开放了读权限,测试阶段可临时使用以下规则:

rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if true;
}
}
}
正式上线前务必调整安全规则,避免数据泄露和恶意操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:06:04