如何将获取的API响应正确地插入表中

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何将获取的API响应正确地插入表中相关的知识,希望对你有一定的参考价值。

我有一个带有自定义标记的google-map。这些标记是公司的徽标。在查询了API之后,我可以使用我感兴趣的容器获得json文件。

问题我遇到的问题是,我一直试图将这些容器注入用户界面上的表中,但不幸的是没有成功。怎么做?

“地图”

API的典型响应以下

[  
      
        "AIS":  
            "MMSI":227441980,
            "TIMESTAMP":"2017-08-11 11:17:37 UTC",
            "LATITUDE":46.1459,
            "LONGITUDE":-1.16631,
            "COURSE":360.0,
            "SPEED":0.0,
            "HEADING":511,
            "NAVSTAT":1,            
            "IMO":0,
            "NAME":"CLEMENTINE",
            "CALLSIGN":"FJVK",
            "TYPE":60,
            "A":0,
            "B":0,
            "C":0,
            "D":0,
            "DRAUGHT":0.0,
            "DESTINATION":"",
            "ETA_AIS":"00-00 00:00",
            "ETA":"",
            "SRC":"TER",
            "ZONE": "North Sea",
            "ECA": true      
        
    
]

在我用来将API提取的值注入表中的代码下面:

ShipTracker.js

import React from 'react';
import  Table  from 'reactstrap';

const shipCompanyMap = 
    MICHIGAN: 'DONJON',
    ATLANTIC SALVOR': 'DONJON',
    STUYVESANT: 'DUTRA'
;

const Ship = ( ship, logoMap, logoClick ) => 
const shipName = ship.AIS.NAME;
const company = shipCompanyMap[shipName];
const img = logoMap[company && company.split(' ').join('').toUpperCase()];
return (
    <div onClick=(event) => logoClick(event, ship)>
        /* Render shipImage image */
        <img src=img alt="Logo" />
    </div>
);
;
export  Ship ;

const ShipTracker = ( ships, setActiveShip ) => 
console.log('These are the ships: ',  ships );

return (
    <div className="ship-tracker">
        <Table className="flags-table" responsive hover>
            <thead>
                <tr>
                    <th>#</th>
                    <th>MMSI</th>
                    <th>TIMESTAMP</th>
                    <th>LATITUDE</th>
                    <th>LONGITUDE</th>
                    <th>COURSE</th>
                    <th>SPEED</th>
                    <th>HEADING</th>
                    <th>NAVSTAT</th>
                    <th>IMO</th>
                    <th>NAME</th>
                    <th>CALLSIGN</th>
                </tr>
            </thead>
            <tbody>
                ships.map((ship, index) => 
                    // const  IMO, NAME, CALLSIGN, HEADING, SOG, MMSI, LONGITUDE, LATITUDE  = ship;
                    // const cells = [ NAME, CALLSIGN, HEADING, SOG, IMO, MMSI, LONGITUDE, LATITUDE ];

                    const 
                        MMSI,
                        TIMESTAMP,
                        LATITUDE,
                        LONGITUDE,
                        COURSE,
                        SPEED,
                        HEADING,
                        NAVSTAT,
                        IMO,
                        NAME,
                        CALLSIGN
                     = ship;

                    const cells = [
                        MMSI,
                        TIMESTAMP,
                        LATITUDE,
                        LONGITUDE,
                        COURSE,
                        SPEED,
                        HEADING,
                        NAVSTAT,
                        IMO,
                        NAME,
                        CALLSIGN
                    ];

                    return (
                        <tr
                            onClick=() => setActiveShip(ship.AIS.NAME, ship.AIS.LATITUDE, ship.AIS.LONGITUDE)
                            key=index
                        >
                            <th scope="row">index</th>
                            cells.map((cell) => <td key=ship.AIS.MMSI>cell</td>)
                        </tr>
                    );
                )
            </tbody>
        </Table>
    </div>
);
;

export default ShipTracker;

下面的文件GoogleMap.js带有<ShipTracker />信息:

class BoatMap extends Component 
    constructor(props) 
        super(props);
        this.state = 
            buttonEnabled: false,
            buttonClickedAt: new Date(),
            progress: 0,
            ships: [],
            type: 'All',
            shipTypes: [],
            activeShipTypes: [],
            logoMap: 
        ;
        this.updateRequest = this.updateRequest.bind(this);
        this.countDownInterval = null;
    

    async componentDidMount() 
        this.countDownInterval = setInterval(() => 
        , 500);

        await this.updateRequest();

        const shipTypeResults = await Client.getEntries(
            content_type: 'comp'
        );
        const shipTypes = shipTypeResults.items.map((data) => data.fields);

        const logoMap = shipTypes.reduce((acc, type) => 
            return 
                ...acc,
                [type.name]: type.images.fields.file.url
            ;
        , );
        // console.log( shipTypes );
        this.setState(
            logoMap
        );
    

    componentDidUpdate(prevProps, prevState) 
        if (this.state.type !== prevState.type) 
            console.log('dropdown value changed for ' + this.state.type);
        
    

    async updateRequest() 
        const url = 'http://localhost:3001/hello';
        // console.log(url);
        const fetchingData = await fetch(url);
        const ships = await fetchingData.json();

        this.setState(
            ships
        );
    

    handleMarkerClick = (event, data) => 
        this.props.setActiveShip(data.AIS.NAME, data.AIS.LATITUDE, data.AIS.LONGITUDE);
    ;

    render() 
        console.log('ships ', this.state.ships);
        return (
            <div className="google-map">
                <GoogleMapReact
                    bootstrapURLKeys= key: 'KEY' 
                    center=
                        lat: this.props.activeShip ? this.props.activeShip.latitude : 37.99,
                        lng: this.props.activeShip ? this.props.activeShip.longitude : -97.31
                    
                    zoom=5.5
                >
                    /* Rendering all the markers here */
                    this.state.ships.map((ship) => (
                        <Ship
                            ship=ship
                            key=ship.AIS.MMSI
                            lat=ship.AIS.LATITUDE
                            lng=ship.AIS.LONGITUDE
                            logoMap=this.state.logoMap
                            logoClick=this.handleMarkerClick
                        />
                    ))
                </GoogleMapReact>
            </div>
        );
    



export default class GoogleMap extends React.Component 
    state = 
        ships: [],
        activeShipTypes: [],
        activeCompanies: [],
        activeShip: null
    ;


    handleDropdownChange = (e) => 
        const shipType = e.target.value;

        if (this.state.activeShipTypes.includes(shipType)) 
            const filteredShipTypes = this.state.activeShipTypes.filter((type) => type !== shipType);
            this.setState(
                activeShipTypes: filteredShipTypes
            );
         else 
            this.setState(
                activeShipTypes: [ ...this.state.activeShipTypes, shipType ]
            );
        
    ;

    setActiveShip = (name, latitude, longitude) => 
        this.setState(
            activeShip: 
                name,
                latitude,
                longitude
            
        );
    ;

    render() 
        return (
            <MapContainer>

                <BoatMap
                    setActiveShip=this.setActiveShip
                    activeShip=this.state.activeShip
                    handleDropdownChange=this.handleDropdownChange
                />
                <ShipTracker
                    ships=this.state.ships
                    setActiveShip=this.setActiveShip
                    onMarkerClick=this.handleMarkerClick
                />
            </MapContainer>
        );
    

我进行了很多研究,发现this sourcethis other source很有用,但不能解决问题。我可能会误解API的响应以及如何注入数据?

感谢您指出正确的方向来解决此问题。

答案

问题是,当您从ship解构属性时,您需要从ship.AIS中获取它们,而不仅仅是ship,因为ship.MMSIship.TIMESTAMP等将是未定义的。

const 
 MMSI,
 TIMESTAMP,
 LATITUDE,
 LONGITUDE,
 COURSE,
 SPEED,
 HEADING,
 NAVSTAT,
 IMO,
 NAME,
 CALLSIGN
 = ship.AIS;
//  ^ correct

以上是关于如何将获取的API响应正确地插入表中的主要内容,如果未能解决你的问题,请参考以下文章

如何正确地将旧日期插入表格?

如何正确地将身份验证令牌放在 GET 请求的标头中

如何将购物车中的多个项目插入表格中?

如何正确地将纬度和经度坐标插入 mySQL 浮点数?

使用xpath web api c#从xml获取数据

如何正确地将集合选择放在 form_tag 中?