繁体   English   中英

如何将获取的 API 数据传递到 HTML 表

[英]How to pass fetched API data to HTML table

我有一个带有自定义标记的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 fetch 中的值注入到表中的代码下方:

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
            };
        }, {});
        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';
        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
    };

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

我一直在研究很多,并遇到了这个来源另一个有用但没有解决问题的其他来源 我是否可能误解了 API 的响应以及如何注入数据?

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

你只需要在解构上更深入一层:

如果您登录ship ,它将是一个类似于{AIS: {...}} 所以,改变这个: const {MMSI, ... } = ship to const {MMSI, ... } = ship.AIS

暂无
暂无

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

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