使用 .map 函数时设置状态

setting state when using a .map function

我想我可能 运行 陷入回调地狱类型的场景,或者这可能是范围问题。一旦 .map 函数完成 运行ning,我想要使用 allLeagues 数组的 setState。问题是,当 .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

.map() returns 一个新数组。您需要在变量中捕获它。在 map 中,你应该有一个函数来对每个元素做一些事情。

allLeagues = this.state.leagueMatchesInfo.map((league, id) => { ... } this.setState({ leagueAL: allLeagues })

然后在map之后setState。

问题是在承诺解决之前您不会更新 allLeagues 数组。然而, setState 在这一切发生之前就被调用了。

我会研究类似 Promise.all() 的内容。然后,您可以在每次调用 fetch 时创建一个承诺数组。然后你可以从你的 Promise.all() 调用 .then 并在 .then.

中设置状态