【问题标题】:How do I call firebase functions from within a react component如何从反应组件中调用 firebase 函数
【发布时间】:2020-03-12 17:00:32
【问题描述】:

我正在尝试研究如何从 react 组件中调用 firebase 函数。

反应组件...

import React from 'react';
import './App.css';
import functions from '../functions/index'

function App() {

    const callFirebaseFunction = event =>{
        var output = functions.returnMessage()
        console.log(output)
    }

    return(
        <div>
            <button onClick={event => callFirebaseFunction()}>call function button</button>
        </div>    
    )

firebase 函数 index.js...

const functions = require('firebase-functions');

exports.returnMessage = functions.https.onCall((data, context) => {
    return {
        output: "the firebase function has been run"
      }
});

希望我的代码能解释我想要做什么。请随时纠正我在这个非常简单的示例中犯的任何其他错误。

我遇到的问题是我无法将任何内容导入到不在 src 文件夹中的组件中,并且 firebase 功能不在此范围内。我真的不想弹出任何东西,因为我假设我有适当的方法来访问我的 firebase 功能,但我根本找不到它。

【问题讨论】:

  • 你为什么不把你的代码移到src
  • Firebase 出于某种原因抱怨我这样做。我简单地尝试了一下,遇到了几个不同的问题,尽管我不记得它们是什么了。我会再次这样运行它以找出问题所在。
  • 我猜你的 react 应用程序是使用 create-react-app 制作的?在src 文件夹中编写所有代码应该没有任何问题,除非您可能也在编写一些服务器端代码。请用与此相关的错误更新您的问题
  • 是的,你是对的。 firebase 函数是否算作服务器端代码?我会在几分钟内添加一些错误。
  • 哦,我刚刚查了一下,是的,它 100% 是 nodejs 的东西。您不能将这些功能导入您的反应应用程序,这是 0 意义。即使你可以,它也不会做任何事情......你到底想做什么?

标签: reactjs firebase google-cloud-functions


【解决方案1】:

我刚刚将 firebase 从 ^4.8.0 更新为 ^7.21.0

现在我可以使用 httpsCallable

【讨论】:

    【解决方案2】:

    根据the documentation,您需要使用客户端的 firebase 库来调用可调用函数。您不应该导入服务器端函数代码,它必须是 deployed to firebase functions 本身——它不会在应用程序的客户端中重用。

    假设你有正确的imported the firebase client SDK into your client code,这意味着我们可以像这样修改callFirebaseFunction

    const callFirebaseFunction = event => {
        const callableReturnMessage = firebase.functions().httpsCallable('returnMessage');
    
        callableReturnMessage().then((result) => {
          console.log(result.data.output);
        }).catch((error) => {
          console.log(`error: ${JSON.stringify(error)}`);
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 2021-02-26
      • 2019-01-09
      • 2021-05-07
      相关资源
      最近更新 更多