【问题标题】:TypeError: _initFirebase__WEBPACK_IMPORTED_MODULE_4__.firebase.database is not a function类型错误:_initFirebase__WEBPACK_IMPORTED_MODULE_4__.firebase.database 不是函数
【发布时间】:2021-09-03 11:46:23
【问题描述】:

我正在尝试将新数据推送到我的Firebase Realtime Database

我有这个initFirebase.js

import * as firebase from 'firebase/app'
import 'firebase/auth'
import 'firebase/database'

const firebaseConfig = {
    apiKey: "AIzaSyBhiHbrO2qUvGDmGN3iX5u-SlpRK_EPlzU",
    authDomain: "table-app-e64c3.firebaseapp.com",
    projectId: "table-app-e64c3",
    storageBucket: "table-app-e64c3.appspot.com",
    messagingSenderId: "102169979497",
    appId: "1:102169979497:web:c8dc8170bd6ce50f4850f8",
    measurementId: "G-6RC7ZQ1177"
  };

  function initFirebase() {
      if (!firebase.getApps.length){
          firebase.initializeApp(firebaseConfig)
      }
  }
  
  initFirebase()

  export { firebase }

我有这个App.js(我粘贴了唯一相关的部分):

import { firebase } from "./initFirebase"
const App = () => {
//...

  const handleAddFormSubmit = (event) => {
    event.preventDefault()
    
    const listRef = firebase.database().ref("Lists")
    const newListRef = listRef.push()
    newListRef.set({
        //Some Data to insert
      })
  }

//...
}

export default App;

但我不断收到此错误:

TypeError: _initFirebase__WEBPACK_IMPORTED_MODULE_4__.firebase.database is not a function

handleAddFormSubmit

  43 |    setContacts(newContacts)
  44 | 
  45 |    //Represent a new record in the database
> 46 |    const listRef = firebase.database().ref("Lists")
     | ^  47 |    const newListRef = listRef.push()
  48 |    newListRef.set({    

我粘贴handleAddFormSubmit 的上述函数中的所有内容都中断了,我一次又一次地无法解决这个问题。我是 React 和 Firebase 的新手,我会感谢解决方案的任何帮助或指导。谢谢。

已解决,编辑: Modular SDK (v9) 的完整文档(与 v8 相比)can be found here

【问题讨论】:

    标签: javascript reactjs firebase firebase-realtime-database


    【解决方案1】:

    显然您安装了新的 Modular SDK (v9),它没有 firebase.database() 语法,但使用了新语法。如果您想保持其余代码不变,请将您的导入更改为兼容库:

    import firebase from 'firebase/compat/app'
    import 'firebase/compat/auth'
    import 'firebase/compat/database'
    

    我建议使用新的 Modular 语法,因为它具有 tree-shaking 的好处。您可以尝试将代码重构为:

    import { initializeApp } form "firebase/app"
    import { getAuth } from "firebase/auth";
    import { getDatabase } from "firebase/database"
    
    const app = initializeApp(firebaseConfig)
    
    const auth = getAuth(app)
    const db = getDatabase(app)
    
    export { auth, db }
    

    然后在app.js:

    import { auth, db } from "./initFirebase"
    import { ref, push, set } from "firebase/database"
    
    const handleAddFormSubmit = (event) => {
      event.preventDefault()
        
      const listRef = ref(db, 'Lists');
      const newItemRef = push(listRef);
      set(newPostRef, {..data});
    }
    

    【讨论】:

    • 感谢详细的解决方案!效果很好:)!
    猜你喜欢
    • 2020-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 2022-01-25
    相关资源
    最近更新 更多