【问题标题】:React + Redux + Firebase: how to deal with a firebase configuration defined and exported as a class?React + Redux + Firebase:如何处理定义并导出为类的 firebase 配置?
【发布时间】:2020-11-17 02:06:40
【问题描述】:

我正在学习如何向 React+Firebase 项目添加身份验证。以前,当我需要导出我的 firebase 配置常量时,我​​曾经这样做过:


const config = {
//...
  };

firebase.initializeApp(config)
const database = firebase.database()
export {database}

然后import {database} from 'path' 我想用它。

但是,在新的身份验证实现中,我有这样的事情:

const config = {
//...
  };

class Firebase {
constructor() {
app.initializeApp(config);

/* Helper */

this.serverValue = app.database.ServerValue;
this.emailAuthProvider = app.auth.EmailAuthProvider;

/* Firebase APIs */

this.auth = app.auth();
this.db = app.database();

//etc
  }

export default Firebase;

所以在另一个文件中,我现在可以import Firebase from 'path' - 但是我不知道如何访问 Firebase 的数据库。 Firebase.db 和 Firebase.database() 不起作用。感谢您的帮助

【问题讨论】:

    标签: reactjs firebase authentication redux


    【解决方案1】:

    回答我自己的问题。怀疑任何人都会有同样的问题,但这里是:

    我们现在正在处理一个类。因此,当我导出 Firebase 时,我并没有将它导出为一个可供使用的对象(就像我以前那样) - 现在我将它导出为一个类。

    所以当我将它导入另一个文件时:import Firebase from 'path' 我必须记住在该文件中创建它的一个实例才能使用它。

    import Firebase from 'path'  //Firebase is not an object, it is a class
    
    const fbInstance = new Firebase(); //creating an instance of the class
    
    const database = fbInstance.db;  //each instance is assigned a db (database) through the constructor (posted earlier)
    

    如果您不太了解,请查看一些 OOP(或 javascript 类)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-23
      • 2018-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多