简体   繁体   中英

How to iterate and render nested objects/arrays from data in React?

I am using react (Im not too experienced with it) and want to render data, the problem is everything is nested - with objects and arrays. I have tried so many different things but its just not working. For example: the data is flight info. For a round trip I have a nested array for each connecting flight and the same back. For other things like departure airport-its again nested differently. Since I want to display multiple flights, I have to iterate through all that when I render the date but I don't know how to. I tried to find something online and have been pretty much staring at my code for a while and I am pretty much lost. If anyone could help, it would be great. I also added the json with the data (I removed some key value pair and left those which are important for the nested/different data structure). Thanks a lot!

data:

       {
        "PricedItineraries": [{
            "AirItinerary": {
                "OriginDestinationOptions": {
                    "OriginDestinationOption": [{
                        "FlightSegment": [{


                            "DepartureAirport": {
                                "LocationCode": "JFK"
                            },
                            "ArrivalAirport": {
                                "LocationCode": "MSP"
                            },

                            "DepartureDateTime": "2018-01-07T07:00:00",
                            "OperatingAirline": {
                                "FlightNumber": 111,
                                "Code": "AA"
                            }
                        }, 


                            {
                            "DepartureAirport": {
                                "LocationCode": "MSP"
                            },
                            "ArrivalAirport": {
                                "LocationCode": "LAX"
                            },                    
                            "DepartureDateTime": "2018-01-07T10:05:00",
                            "OperatingAirline": {
                                "FlightNumber": 444,
                                "Code": "SY"
                            }
                        }],
                        "ElapsedTime": 485
                    }, 

                    // ... same structure below for trip back  ...

                       {
                        "FlightSegment": [{

                            "DepartureAirport": {
                                "LocationCode": "LAX"
                            },
                            "DepartureTimeZone": {
                                "GMTOffset": -8
                            }
                        }, 

                            {
                            "DepartureAirport": {
                                "LocationCode": "SEA"
                            },

                            "DepartureTimeZone": {
                                "GMTOffset": -8
                            }
                        }],
                        "ElapsedTime": 745
                    }]
                },

                "DirectionInd": "Return"
            },

            "AirItineraryPricingInfo": {
                "PTC_FareBreakdowns": {
                    "PTC_FareBreakdown": {
                        "PassengerTypeQuantity": {
                            "Quantity": 1,
                            "Code": "ADT"
                        },
                        "Endorsements": {
                            "NonRefundableIndicator": true
                        }
                    }
                },
                "FareInfos": {
                    "FareInfo": [{
                        "TPA_Extensions": {
                            "SeatsRemaining": {
                                "BelowMin": false,
                                "Number": 4
                            }
                        }
                    }
                    }]
                },
                "ItinTotalFare": {
                    "TotalFare": {
                        "CurrencyCode": "USD",
                        "DecimalPlaces": 2,
                        "Amount": 341.61
                    },
                    "Taxes": {
                        "Tax": [{
                            "CurrencyCode": "USD",
                            "DecimalPlaces": 2,
                            "TaxCode": "TOTALTAX",
                            "Amount": 66.25
                        }]
                    }
                }
            },
            "TicketingInfo": {
                "TicketType": "eTicket"
            }
        }, {
            "AirItinerary": {
             ..same structure again...repeats multiple times

React Component:

   class Search extends React.Component {
        constructor(props){
            super(props);
            this.state={
                origin:'',
                destination:''
                  ...

               // flightinfo
                airlineCodeToDestination:[],
                airport:[],
                departureTime:[],
                arivalTime:[],
                totalDuration:[],
                price:[],
                flightInfo:[]
            }
            this.handleInput=this.handleInput.bind(this);
            this.testing=this.testing.bind(this);
        }
        testing(e){
            this.setState({
                [e.target.name]:e.target.value
            })
        }

        handleInput(e){
            e.preventDefault();
            regularSearchData(this.state.origin, this.state.destination, this.state.departuredate, this.state.returndate)
                .then(function(response){
                    return response.data.PricedItineraries;
            })
               .then(res => {
                    let response=res,
                        allFares=[],
                        airlineCode=[],
                        airport=[],
                        x=[],
                        departureTime=[],
                        arivalTime=[],
                        totalDuration=[];
                 response.map(function(item){

                    //this here are just a few of my tries 

                        allFares.push(item.AirItineraryPricingInfo.ItinTotalFare.TotalFare.Amount);
                        x.push(item.AirItinerary.OriginDestinationOptions.OriginDestinationOption);
                        airlineCode.push(item.AirItinerary.OriginDestinationOptions.OriginDestinationOption[0].FlightSegment[0].MarketingAirline.Code);
                    });

                    this.setState({
                        price:allFares,
                        airlineCodeToDestination:airlineCode,
                        flightInfo:x
                    })
            })
        }
        render () {
            const flights = this.state.flightInfo.map((item, i) => {
                return (
                    <div>
                        <div key={i}> {item} </div>
                    </div>);
            });
            return (
                <div>
                    {flights}
                    <form onSubmit={this.handleInput}>
                    <input type="text" name="origin"  value={this.state.origin} onChange={this.testing} />
                    <input type="text"  name="destination" value={this.state.destination} onChange={this.testing}/>
                    <input type="date" name="departuredate" value={this.state.departuredate} onChange={this.testing} />
                    <input type="date" name="returndate" value={this.state.returndate} onChange={this.testing} />
                    <input type="submit" value="Submit" />
                    </form>
                </div>
            )
        }
    }

    export default Search;

In your handleInput method, you are creating new arrays and adding data to them.Then you are calling setState to set these new arrays as your new state, which will result in the old state getting removed and only the new arrays showing up. If you want your old data to persist, you would need to change the declaration of the variables in the code as follows:

                    ....
                    allFares=[...this.state.allFares],
                    airlineCode=[...this.state.airlineCode],
                    ....

This will create copies of the exiting arrays from your state and when you push your new item in them and then call setState to set them, you will not lose your existing data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM