我想我可能会遇到一个回调地狱类型的场景,或者这可能是范围问题。一旦.map函数运行完毕,我希望setState具有allLeagues
数组。问题是,当.map
函数完成并运行this.setState({leagueAL: allLeagues)}
时,状态将设置为空数组。我不想在.map中运行this.setState
并多次设置它。关于如何使数据持续进入状态的任何想法?
getLeagueMatches = () => {
let allLeagues = []
if(this.state.leagueMatchesInfo != null){
this.state.leagueMatchesInfo.map((league, id) => {
let leagueID = league.league_id;
fetch(`https://apifootball.com/api/?action=get_events&from=2017-09-11&to=2017-09-11&league_id=${leagueID}&APIkey=<APIKey>`)
.then(res => res.json())
.then(event => {
//console.log(event)
if(event.error){
//console.log(event.error)
}else{
league.matches = true;
//console.log(league)
allLeagues = [...allLeagues, league]
}
})
console.log(allLeagues)
})
this.setState({
leagueAL: allLeagues
})
}//end if(65)
};//end renderItem
答案 0 :(得分:1)
.map()返回一个新数组。您需要在变量中捕获它。在map中,你应该有一个函数可以对每个元素执行某些操作。
allLeagues = this.state.leagueMatchesInfo.map((league, id) => {
...
}
this.setState({
leagueAL: allLeagues
})
然后在地图后面设置。
答案 1 :(得分:1)
问题是,在承诺解决之前,您不会更新allLeagues
数组。但是,在发生任何此类事件之前,都会调用setState
。
我会调查类似Promise.all()
的内容。然后,您可以在每次调用fetch
时创建一个承诺数组。然后,您可以从.then
拨打Promise.all()
,并在.then
内设置状态。