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

React Native中Firebase Database配置及写入报错求助

问题分析与修复方案

核心错误点

  1. 集合引用创建错误:collection.apply(db, 'recipe') 使用方式错误,apply 第二个参数必须是数组,这里直接调用 collection 函数即可。
  2. Firebase API 混淆:你混淆了 Firestore 和 Realtime Database 的 API——你在 Firestore 创建了集合,但代码里用了 Realtime Database 的 ref/set 方法,两者完全不兼容。
  3. 对象语法错误:食谱对象中带空格的键未加引号,且键值对之间缺少逗号,导致语法错误。

步骤1:修正 Firebase 配置文件(firebaseConfig.js)

import { initializeApp } from "firebase/app";
import { getFirestore, collection } from 'firebase/firestore'

const firebaseConfig = {
  apiKey: "AIzaSyBWDFmAF4Bx7PpSvccF_ebRe2kBWGqj11c",
  authDomain: "recipegenerator-918a7.firebaseapp.com",
  projectId: "recipegenerator-918a7",
  storageBucket: "recipegenerator-918a7.appspot.com",
  messagingSenderId: "743737873782",
  appId: "1:743737873782:web:8036f2ed1cae24f60d5657",
  measurementId: "G-Z9WK0Q0ML3"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);

export const db = getFirestore(app);
// 正确创建并导出Firestore集合引用
export const recipesCol = collection(db, 'recipe');

步骤2:修正 App.js 中的保存功能

import { recipesCol } from './components/firebaseConfig';
// 导入Firestore的添加文档方法
import { addDoc } from 'firebase/firestore';
import { Button } from 'react-native';

const saveRecipe = async () => {
  try {
    // 使用Firestore的addDoc添加文档到集合
    await addDoc(recipesCol, {
      Ingredients: 'ingredient 1',
      Instructions: "instruction 1",
      NutritionalInfomation: "Nutrition 1",
      // 带空格的键需要用引号包裹
      "Recipe Title": "title 1"
    });
    console.log("食谱保存成功");
  } catch (error) {
    console.error("保存失败:", error);
  }
};

// 正确渲染Button组件
return <Button title="Save Recipe" onPress={saveRecipe} />;

关键说明

  • Firestore 是文档-集合型数据库,添加数据用 addDoc(自动生成文档ID)或 setDoc(自定义文档ID),而非 Realtime Database 的 set 方法。
  • 集合引用只能用于 Firestore API,不能传入 Realtime Database 的 ref 方法中,这是你出现类型错误的直接原因。
  • 确保所有依赖安装正确:执行 npm install firebase(若使用web版Firebase库)或对应 React Native Firebase 依赖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 05:53:26