【发布时间】:2018-07-14 05:05:42
【问题描述】:
我正在使用带有 axios 的 React 进行外部 API 调用,循环遍历数组中的每个对象,并传回 API 调用。在循环内部,我有一个承诺,它调用了另一个返回对象的函数。我想使用这个对象返回的值,并将它们分配给循环外的一个变量,该变量是一个用于设置状态的数组,但我似乎不能这样做,因为它总是空的?希望我下面代码中的 cmets 可以帮助您理解我的问题。
let self = this;
this.instance.get('/fixtures?timeFrame=n1').then((fixtures) => {
// get all fixtures
const allFixtures = fixtures.data.fixtures;
// create valid fixtures array to add all fixture details to pass to fixtures state
let validFixtures = [];
// loop through all fixture objects in allFixtures array
for (var i = 0; i < (allFixtures.length); i++) {
// check if valid fixture, returns true or false
let isValid = self.isValid(allFixtures[i]);
// if fixture is valid
if (isValid) {
// get id of fixture to pass through to fixture route with id query
let fixtureId = allFixtures[i]._links.self.href.split('v1/')
.pop();
// home teams name
let homeTeam = allFixtures[i].homeTeamName;
// away teams name
let awayTeam = allFixtures[i].awayTeamName;
// call head2head function to get all previous results from the two teams playing and returns average score
// returns as object, example: { 'homeTeamAvgScore': 2, 'awayTeamAvgScore': 1 }
self.getHead2Head(fixtureId, homeTeam,
awayTeam).then((avg) => {
//in here i want to push object into validFixtures array along with homeTeam and awayTeam as named values
return validFixtures.push({
'homeTeam': homeTeam,
'awayTeam': awayTeam,
'homeTeamAvgScore': avg.homeTeamAvgScore,
'awayTeamAvgScore': avg.awayTeamAvgScore
})
});
}
}
//validFixtures is empty???
//How else can push to array and then later setState to fixtures with validFixtures array???
self.setState({
fixtures: validFixtures
});
}).catch((error) => {
console.log(error);
});
}
【问题讨论】:
-
在self.getHead2Head前加一个“return”关键字,应该可以解决你的问题
-
@GaneshKarewad 这似乎在第三次迭代后停止循环。
allFixtures数组的长度是34但只循环了3次? -
应该是 return Promise.all(allFixtures,(fixture) =>{ // let homeTeam = fixture.homeTeam let awayTeam = fixture.awayTeam return self.getHead2Head(fixtureId, homeTeam, awayTeam).then ((avg) => { return validFixtures.push({ 'homeTeam': homeTeam, 'awayTeam': awayTeam, 'homeTeamAvgScore': avg.homeTeamAvgScore, 'awayTeamAvgScore': avg.awayTeamAvgScore }) }); }) 你可能会必须修改此代码,因为我在没有 js 编译器或解释器的手机上回答这个问题。希望对你有帮助
-
长话短说使用 return promise.all 而不是 for 循环
标签: javascript reactjs promise axios es6-promise