【问题标题】:React Native: firestore/firebase Expected first argument to collection() to be a CollectionReference... how?React Native:firestore/firebase 期望 collection() 的第一个参数是 CollectionReference ......如何?
【发布时间】:2021-12-21 15:05:14
【问题描述】:

所以我有一个简单的 React Native 应用程序,我使用 Expo 创建并在我的个人 Android 设备上进行调试。

我已将 firebase/firestore 包含到我的应用程序中,现在正尝试在单击按钮时将对象添加到 firestore。

这是我的代码:

firebaseConfig.js:

import { initializeApp } from '@firebase/app';

var config = {
    ...
}
  
const app = initializeApp(config);

export default app;

组件:

从'../firebaseConfig'导入{应用}; 从'firebase/firestore/lite'导入{getFirestore}; 从“firebase/firestore”导入 { doc、setDoc、collection、query、where、getDocs、initializeFirestore }; ...

导出默认函数 Component() { const firestoreDb = getFirestore(app);

// this function is called when clicking a button
const onAddListPress = () => {
    setDoc(doc(firestoreDb, "cities", "LA"), {
        name: "Los Angeles",
        state: "CA",
        country: "USA"
    });
}

}

这会引发以下错误:

Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore

上面的这段代码(在 onPress 中)是从官方的 firestore 文档复制而来的,这里: https://firebase.google.com/docs/firestore/manage-data/add-data#set_a_document

有人知道为什么这不起作用吗?

【问题讨论】:

    标签: javascript firebase react-native google-cloud-firestore


    【解决方案1】:

    我建议您编辑您的帖子并删除 firebaseConfig 配置密钥,或者删除您的 Firebase 应用并从 Firebase 控制台创建一个新应用以保护您的应用。我尝试使用 React 复制您的应用程序,但收到了相同的错误消息。我进行了两项更改以纠正错误。第一个在firebaseConfig file里面,默认导出需要改成命名导出:

    import { initializeApp } from "firebase/app"
    
    const firebaseConfig = {
        //Project configuration keys
    };
    
    const app = initializeApp(firebaseConfig);
    
    export { app }; // Change from a default to a named export
    

    此外,组件内的所有导入都应该来自完整的 Javascript SDK,而不是精简版。精简版有一些 limitations 可能导致此 specific 错误。

    import { app } from "./firestore-config";
    import { getFirestore, getDoc, doc } from "firebase/firestore";
    import './App.css';
    
    export default function App() {
      const firestoreDB = getFirestore(app);
      const docRef = doc(firestoreDB, "users", "testUser1");
    
      const getData = async () => {
        const data = await getDoc(docRef);
        console.log(data);
      }
    
      getData();
      return <div className="App"></div>;
    }
    

    如果您使用 yarn 管理依赖项,您可能还想查看此 GitHub issue

    【讨论】:

      猜你喜欢
      • 2021-11-08
      • 2022-07-02
      • 2021-11-01
      • 2021-11-02
      • 1970-01-01
      • 2021-11-16
      • 2021-11-01
      • 2023-03-15
      • 1970-01-01
      相关资源
      最近更新 更多