首页 > 解决方案 > 从服务 Javascript 接收变量 - React Hooks

问题描述

我有一个按钮元素,它在我的工作区中调用另一个 javascript 文件。

      <Button
        onClick={() =>
            SendRegister(
              {
                registrationType: 'email',
                latitude: 55,
                longitude: 100,
                distance: 100,
                email: 'email@testemail.com'
              }
            )
        }>
        Set Up Notifications
      </Button>

在另一个 javascript 文件中,我正在将收到的信息写入 firebase:

import React, { useState, useEffect } from "react";
import firebase from "./firebase";

    function SendRegister(props) {
      alert('in Send register');
      alert(JSON.stringify(props));
      var db = firebase.firestore();

      if (props.registrationType === 'email') {
        db.collection("emailAlerts")
          .add({
            email: props.email,
            latitude: props.latitude,
            longitude: props.longitude,
            distance: props.distance,
           status: "active"
          })
          .then(function(docRef) {
            return docRef.id;
          })
          .catch(function(error) {
            return("Error adding document: " + error);
          });
    }

    }

    export default SendRegister;

在 firebase 中,我看到记录成功写入,但是我不确定如何将函数的返回传递回我调用onClick.

我曾尝试将 SendRegister 函数包装在useStateconst 中setStatus(SendRegister...以捕获返回,但我在返回中收到了undefined返回。我还查看了提升状态,这对元素/组件有意义,但不确定它如何适合SendRegister. 我相信 redux 并且useContext是一种选择,但我想确保没有一种更简单的方法可以将变量从一个页面传递到另一个我没有考虑的页面。

标签: javascriptreactjsfirebasegoogle-cloud-firestorereact-hooks

解决方案


我假设您正在尝试docRef.id在父组件中获取返回值。由于里面的操作SendRegister是异步的,你应该返回一个SendRegister父组件可以监听的promise。

export default class componentName extends Component {

  async handleSendRegister(params){
    try {
      const docRefId = await SendRegister(params)

      // docRefId is now available here
    } catch (error) {
      console.log(error)
    }
  }

  render() {
    return (
      <Button
        onClick={() =>
          this.handleSendRegister(
            {
              registrationType: 'email',
              latitude: 55,
              longitude: 100,
              distance: 100,
              email: 'email@testemail.com'
            }
        )
    }>
    Set Up Notifications
  </Button>
    )
  }
}

并且SendRegister应该是一个简单的异步函数。

async function SendRegister(props) {
  try {
    if (props.registrationType === 'email') {

      const docRef = await db.collection("emailAlerts")
      .add({
        email: props.email,
        latitude: props.latitude,
        longitude: props.longitude,
        distance: props.distance,
       status: "active"
      })

      return docRef.id
    }

   } catch (error) {
      throw Error(error.message)
  }

}

export default SendRegister;

推荐阅读