-->

setting state when using a .map function

2020-04-21 04:53发布

问题:

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

回答1:

.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 })

Then setState after the map.



回答2:

The issue is that you're not updating the allLeagues array until the promises have resolved. However, setState is being called before any of this even happens.

I would look into something like Promise.all(). Then you can create an array of promises with each call to fetch. Then you can call .then off your Promise.all() and set the state within the .then.