我有一个按钮元素,它调用工作区中的另一个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是一种选择,但我想确保没有一种更简单的方法将变量从一个页面传递到另一个页面,而我并没有考虑。
发布于 2020-03-01 07:25:26
我假设您正在尝试在父组件中获取返回值docRef.id。由于SendRegister内部的操作是异步的,所以您应该从SendRegister返回一个承诺,父组件可以监听该承诺。
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;发布于 2020-03-01 07:02:49
可以在onClick处理程序上传递回调方法,如下所示:
SendRegister(
{
registrationType: 'email',
latitude: 55,
longitude: 100,
distance: 100,
email: 'email@testemail.com',
callback: ()=>{// code to executed on promise resolve}
}您可以在promise.then()中调用这个函数,因为它将是道具的一部分。
https://stackoverflow.com/questions/60472701
复制相似问题