简体   繁体   English

如何从React中的数据迭代和渲染嵌套的对象/数组?

[英]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. 我正在使用react(我对此不太有经验),并且想要呈现数据,问题是一切都嵌套了-带有对象和数组。 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). 我还添加了带有数据的json(我删除了一些键值对,并保留了对嵌套/不同数据结构很重要的键值对)。 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. handleInput方法中,您正在创建新数组并向其中添加数据,然后调用setState将这些新数组设置为新状态,这将导致删除旧状态并仅显示新数组。 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. 这将为您的状态创建现有数组的副本,当您在其中推入新项,然后调用setState进行设置时,不会丢失现有数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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