首页 > 解决方案 > firebase.functions() 在 React 中未定义,而 firebase.firestore() 可以工作

问题描述

因此,我正在开发一个使用 Firebase 来实现许多功能的 React 项目。现在我正在尝试在其中使用一些 HTTPS 可调用函数。

但似乎我导入“firebase/functions”模块的方式不正确。它给了我这个错误:

TypeError: Cannot read property 'httpsCallable' of undefined

以下是我如何进行导入和设置:

import app from 'firebase/app';
import 'firebase/auth';
import 'firebase/firestore';
import 'firebase/functions';

const config = {
   // the config info here
};

  class Firebase {
    constructor() {
      app.initializeApp(config);
      this.auth = app.auth();
      this.db = app.firestore();
      this.functions = app.functions();
    }

    // trying to call the function
    doCreatePlanner = this.functions.httpsCallable('createPlanner')

应用 Doug 的建议后:

您试图在构造函数中定义它之前访问 this.functions 。要摆脱错误消息,您可以将对 httpsCallable 的调用移动到构造函数中:

我这样做了:

class  Firebase {
    constructor() {
        app.initializeApp(config);
        this.auth = app.auth();
        this.db = app.firestore();
        // Get the callable function reference here
        this.createPlannerCloudFunc = app.functions().httpsCallable('createPlanner')
    }
    
    doCreatePlanner = (input) =>  this.createPlannerCloudFunc(input)

它有效!

但我还是有点困惑。

创建/使用类时,不应该总是首先调用构造函数吗?

所以在 doCreatePlanner 函数中,this.functions应该持有app.functions(),对吧?

我可以在课堂上执行这样的功能,其中this.db包含app.firestore()

doUpdateRecord = (userRecord) =>
    // create the user in firestore
    this.db.collection(`users`).doc(userRecord.uid).set({
        // record info here
    })

标签: javascriptreactjsfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


引用this.functions = app.functions()指向对象的集合。指针不保存函数,因为这些对象的类型不同。一方面你有一个实体,另一方面你有一个对象列表。

this.db可以保持,因为这些属性的app.firestore()类型是相同的。


推荐阅读