.map函数时设置状态 [英] setting state when using a .map function
问题描述
我认为我可能会遇到回调地狱类型的场景,或者这可能是范围的问题.一旦.map函数完成运行,我想使用allLeagues
数组的setState.问题是,完成.map
函数并运行this.setState({leagueAL: allLeagues)}
时,状态设置为空数组.我不想在.map中运行this.setState
并将其设置多次.关于如何使数据持久保存状态的任何想法?
I think I may running into a callback hell type scenario or this may be an issue with scope. I want setState with allLeagues
array once the .map function is finished running. Problem is, when the .map
function is done and this.setState({leagueAL: allLeagues)}
is ran, the state is set to an empty array. I do not want to run this.setState
inside the .map and set it multiple times. Any thoughts on how I can make the data persist into the state?
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
推荐答案
.map()返回一个新数组.您需要将其捕获到变量中.在map中,您应该有一个对每个元素都执行某些操作的函数.
.map() returns a new array. You'll need to catch it in a variable. In map, you should have a function that does something on each element.
allLeagues = this.state.leagueMatchesInfo.map((league, id) => {
...
}
this.setState({
leagueAL: allLeagues
})
allLeagues = this.state.leagueMatchesInfo.map((league, id) => {
...
}
this.setState({
leagueAL: allLeagues
})
然后在地图后设置setState.
Then setState after the map.
这篇关于.map函数时设置状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!