我使用React Table从API获取数据并在表中填充它。我进行API调用并获取数据。获得数据后,我提取一个包含电子邮件ID的字段,然后创建一个数组(emailList)。现在我想在之后的POST API调用中使用emailList中的数据作为正文的一部分。因此,在下面的代码中,POST调用下的recipients参数应该包含emailList的数据。 emailList在render方法中全局声明为空数组。使用我当前的设置,由于范围问题,我得到一个未定义的错误。如何在POST调用下访问该值?我已经经历了几个范围StackOverflow的答案并尝试但没有得到结果。
columns: [
{
filterable: false,
Header: 'Action',
accessor: 'action',
Cell: (e) => (
<button
onClick={() => {
axios.get(URL, {
headers: {
'content-type': 'application/json',
'Name' : user.Name,
},
responseType: 'json',
})
.then((response) => {
let responseData = response.data.data;
function getEmailList(input, email) {
var output = [];
for (var i=0;i<input.length; ++i)
output.push(input[i][email]);
return output;
}
emailList = getEmailList(responseData, "email");
function fetchEmail() {
this.emailList = getEmailList(responseData, "email");
}
});
//console.log(new fetchEmail().emailList);
//Unable to get the value of emailList here
axios({
method: 'post',
url: URL2,
headers: {
'content-type': 'application/json',
'Name' : user.Name,
},
data: {
"topic": "product",
"message": {
"sender": "user1@xyz.com",
//For illustration I have hardcoded the email arrays for recipients
"recipients": ["support1@xyz.com", "support2@xyz.com"],
"data": {
"text": "refresh"
},
"attachment": null,
"type": "",
},
},
})
答案 0 :(得分:1)
我认为这是一个竞赛问题(也就是说你试图在电子邮件到达浏览器之前发布),所以你需要更改帖子等待获取的代码。这可以通过承诺轻松完成:
{
//a cache
let promise;
//a promising getter:
function getEmails (){
//if cached return
if( promise ) return promise;
//else await the request
return promise = axios.get(URL,{/*options*/}).then( response => response.data.data.map(obj => obj.email));
}
}
现在我们可以做到:
getEmails().then( console.log);
getEmails().then( console.log);
两个调用都将返回相同的promise,因此只有一个请求,但我们可以多次调用它。例如,我们可以在执行POST之前调用它:
getEmails().then( emails => {
axios({
//...
data:{
message:{
recipients: emails
}
}
});
});