首页 > 解决方案 > Firebase.collection 不是函数

问题描述

Net Ninja 的 React Redux 和 Firebase 教程(2018)

目前正在完成本教程,并在他的教程的5:56中,他在 projectActions.js 中。提供的代码是我的代码的精确副本。但是我收到此错误:

TypeError: firebase.collection is not a function

这是我的代码:

export const createProject = (project) => {
    return (dispatch, getState, { getFirebase, getFirestore}) => {
        //make an async call to firebase
        const firebase = getFirestore();
        firebase.collection('projects').add({
            ...project,
            authorFirstName: 'Net',
            authorLastName: 'Ninja',
            authorID: 12345,
            createdAt: new Date(),
        }).then(() => {
            dispatch({ type: 'CREATE_PROJECT', project});
        }).catch((err) => {
            dispatch({ type: 'CREATE_PROJECT_ERROR', err});
        })
    }
}; 

浏览了 Firebase 的文档,但无济于事,所以不确定如何解决此错误

谢谢你的帮助

编辑 1

根据要求,我的配置文件(数据已删除):

// Import the functions you need from the SDKs you need
import { initializeApp } from 'firebase/app';
import { getAnalytics } from 'firebase/analytics';
import firebase from 'firebase/compat/app';
import 'firebase/firestore';
import 'firebase/auth';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);


export default firebase;

“firestore”返回的对象如下所示: 'console.log(firestore)' 的结果

标签: javascriptfirebasegoogle-cloud-firestorereact-redux

解决方案


您似乎安装了新的 Modular SDK ( V9.0.0+) 并遵循使用旧名称空间语法的旧教程。我建议遵循文档并切换到较新的语法(文档还包含使用较旧语法的示例)。尝试将代码重构为:

// Import the functions you need from the SDKs you need
import { initializeApp } from 'firebase/app';
import { getAnalytics } from 'firebase/analytics';
import { getAuth } from 'firebase/auth';
import { getFirestore } from 'firebase/firestore'

const firebaseConfig = {
    apiKey: "",
    authDomain: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: "",
    appId: "",
    measurementId: ""
};

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

export const auth = getAuth(app);
export const firestore = getFirestore(app)
import { firestore } from '../path/to/config/file';
import { collection, addDoc } from "firebase/firestore"; 

export const createProject = (project) => {
  return (dispatch, getState, { getFirebase, getFirestore}) => {
    //make an async call to firebase
    
    addDoc(collection(db, "projects"), {
      ...projectData
    }).then(() => {
      dispatch({ type: 'CREATE_PROJECT', project});
    }).catch((err) => {
      dispatch({ type: 'CREATE_PROJECT_ERROR', err});
    })
  }
}; 

推荐阅读