我在这里尝试从嵌套的axios调用中获取数据。它可以从两个axios调用中获得响应。
但是我无法在第二个axios调用中更新prize_pool。能够 有人在这方面帮助我
getAllLeague() {
axios.get(BASE_URL + 'leagues').then((response) => {
var arrData = [];
for(var i=0; i<response.data.length; i++) {
var data = {
"leagueid": response.data[i].leagueid,
"description": response.data[i].description,
"itemdef": response.data[i].itemdef,
"name": response.data[i].name,
"tournament_url": response.data[i].tournament_url,
"prize_pool" : ''
}
axios.get(BASE_URL + 'getTournamentPrizePool/' + response.data[i].leagueid).then((response) => {
data.prize_pool = response.data.prize_pool;
}).catch((error) => {
console.log(error);
});
arrData.push(data);
}
console.log(arrData);
this.setState({
leagueList : arrData
});
}).catch((error) => {
console.log(error);
});
}
答案 0 :(得分:0)
原因
this.setState({
leagueList : arrData
});
将在第二个axios完成之前运行。尝试这个。使用Promise.all更干净。希望对您有帮助。
getAllLeague() {
axios.get(BASE_URL + 'leagues').then((response) => {
const promises = response.data.map(item => {
const formData = {
"leagueid": response.data[i].leagueid,
"description": response.data[i].description,
"itemdef": response.data[i].itemdef,
"name": response.data[i].name,
"tournament_url": response.data[i].tournament_url,
"prize_pool" : ''
}
const url = BASE_URL + 'getTournamentPrizePool/' + item.leagueid
return axios.get(url).then(res => {
return {
...formData,
prize_pool: res.data.prize_pool,
}
}).catch((error) => {
console.log(error);
})
})
Promise.all(promises).then(arrData => {
this.setState({
leagueList : arrData
});
})
}).catch((error) => {
console.log(error);
});
}
答案 1 :(得分:0)
这是答案。在内部axios中调用API时需要使用async和await。
getAllLeague() {
axios.get(BASE_URL + 'leagues').then(async (response) => {
var arrData = [];
for(var i=0; i<response.data.length; i++) {
var data = {
"leagueid": response.data[i].leagueid,
"description": response.data[i].description,
"itemdef": response.data[i].itemdef,
"name": response.data[i].name,
"tournament_url": response.data[i].tournament_url,
"prize_pool" : ''
}
await axios.get(BASE_URL + 'getTournamentPrizePool/' + response.data[i].leagueid).then((response) => {
data.prize_pool = response.data.prize_pool;
})
arrData.push(data);
}
console.log(arrData);
this.setState({
leagueList : arrData
});
}).catch((error) => {
console.log(error);
});
}