【问题标题】:Receive Variable from Service Javascript - React Hooks从服务 Javascript 接收变量 - React Hooks
【发布时间】:2020-06-13 19:06:23
【问题描述】:

我有一个按钮元素,它在我的工作区中调用另一个 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 函数包装在 useState const 中,例如 setStatus(SendRegister... 以捕获返回,但我在返回中收到了 undefined。我也查看了提升状态,这对于元素/组件是有意义的,但不确定它如何适合像 SendRegister 这样的函数。我相信 redux 和 useContext 是一种选择,但我想确保没有一种更简单的方法可以将变量从一个页面传递到另一个页面,而我没有考虑过。

【问题讨论】:

    标签: javascript reactjs firebase google-cloud-firestore react-hooks


    【解决方案1】:

    我假设您正在尝试在父组件中获取返回值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;
    

    【讨论】:

    • 谢谢。我选择了你的答案,但我确实必须修改它以使用功能组件和主要组件的钩子。如果您可以更新答案以将上述内容包含在钩子中(唯一真正的变化是功能组件中的异步句柄寄存器必须是异步函数句柄寄存器)。带有更新状态的钩子示例,例如 setDocRefId。
    【解决方案2】:

    您可以在 onClick 处理程序上传递回调方法,例如:

    SendRegister(
              {
                registrationType: 'email',
                latitude: 55,
                longitude: 100,
                distance: 100,
                email: 'email@testemail.com',
                callback: ()=>{// code to executed on promise resolve}
              }
    

    你可以在 promise.then() 中调用这个函数,因为它是 props 的一部分。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-06-19
      • 1970-01-01
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 2015-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多