我有一个按钮元素,可以调用工作区中的另一个 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
code> 回到返回中。我也查找了提升状态,这对于元素/组件有意义,但不确定它如何适合像 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;
关于javascript - 从服务 Javascript 接收变量 - React Hooks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60472701/