javascript - 从服务 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 函数包装在useState
const 中setStatus(SendRegister...
以捕获返回,但我在返回中收到了undefined
返回。我还查看了提升状态,这对元素/组件有意义,但不确定它如何适合SendRegister
. 我相信 redux 并且useContext
是一种选择,但我想确保没有一种更简单的方法可以将变量从一个页面传递到另一个我没有考虑的页面。
解决方案
我假设您正在尝试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;
推荐阅读
- apache-kafka - Kafka Streaming 应用程序会根据 Kafka 主题中可用的分区数量自动创建组中的消费者吗?
- r - 从数据中估计噪声参数
- network-programming - 从 NFQUEUE 返回 netfilter 后如何强制重新路由数据包
- image - “无法转换:'_Uri'的实例”在flutter web上的cloud firestore最新版本上上传图像时出错
- database - 关于搜索引擎自动完成的问题
- ios - Firebase 可选崩溃未正确显示
- c# - TCP 套接字客户端\服务器请求响应
- c# - 如何根据 xamarin.forms 中的条件更改条目的线条颜色
- r - 在 R 中使用 for 循环保存数据帧
- arrays - 将 ORDS 连接到 Angular