如何通过api获取数据并使用它呈现子组件-Google Maps

时间:2019-06-13 20:07:30

标签: javascript reactjs api google-maps synchronization

我必须归档:eventsMapPage.js(主要)和Maps.js(子)。

getEvents = async () => {
const requestResponse = await request(BASE_API_URL + "/api/events", { method: "GET", headers: {}, body: {} });
this.state.eventList = requestResponse.data;
console.log('getEvents');
console.log(this.state.eventList);
}

//fetching data from api in parent
```getEvents = async () => {
const requestResponse = 
await request(BASE_API_URL + "/api/events", {method:"GET", headers: {}, body: {} });
     this.state.eventList = requestResponse.data;
}
```
//Sent state with fetched data
```
<GoogleApiWrapper eventList={this.state.eventList} ></GoogleApiWrapper>
```

//Send data
```
let markerList = []

export class MapContainer extends Component {
    constructor(props) {
        super(props);
        this.state = {};
        markerList = props.eventList;
```
//I want to put this fetched data to  Markers
```
return (
            <Map google={google} zoom={14} onClick={this.onMapClick} style={mapStyles} initialCenter={initialCenter}>
                {
                    markerList.map(marker => {
                        return (
                            <Marker
                                key={marker.id}
                                onClick={this.onMarkerClick}
                                title={marker.title}
                                name={marker.name}
                                position={{
                                    lat: marker.lat,
                                    lng: marker.lng
                                }}
                            />
...
```

实际上,我只想在Google地图中使用来自网络api的标记。当我发送带有数据的硬编码arrar {}时,它可以工作,但是当我使用此api发送时。首先渲染孩子,然后从api获取。因此我的地图上没有任何标记。

我了解到:

a)componentWillMount

b)谷歌地图上的事件,例如onChange或onBoundsChanged,但我不知道如何在我的项目中使用它。

通常在WPF中,我具有约束力,在这里google maps很奇怪。数据到来时,JS应该自动刷新。如何从api获取标记?

2 个答案:

答案 0 :(得分:0)

main.js

import React from 'react';
import GoogleMapsWrapper from './GoogleMapsWrapper.js';
import { Marker } from 'react-google-maps';
import MarkerClusterer from "react-google-/lib/components/addons/MarkerClusterer";

class DemoApp extends React.Component {
    componentWillMount() {
        this.setState({ markers: [] })
    }

    componentDidMount() {
       const url = [
           // Length issue
           `https://gist.githubusercontent.com`,
           `/farrrr/dfda7dd7fccfec5474d3`,
           `/raw/758852bbc1979f6c4522ab4e92d1c92cba8fb0dc/data.json`
           ].join("")

       fetch(url)
       .then(res => res.json())
       .then(data => {
           this.setState({ markers: data.photos });
       });
    }

    render () {
        return (
            <GoogleMapsWrapper
                googleMapURL="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places"
                loadingElement={<div style={{ height: `100%` }} />}
                containerElement={<div style={{ height: `400px` }} />}
                mapElement={<div style={{ height: `100%` }}
                defaultZoom={3}
                defaultCenter={{ lat: 25.0391667, lng: 121.525 }}>
                <MarkerClusterer
                    averageCenter
                    enableRetinaIcons
                    gridSize={60}>
                    {this.state.markers.map(marker => (
                        <Marker
                            key={marker.photo_id}
                            position={{ lat: marker.latitude, lng: marker.longitude }}
                        />
                    ))}
                </MarkerClusterer>
            </GoogleMapsWrapper>
         );
    }

}

GoogleMapsWrapper.js

import React from 'react';
import { GoogleMap,withGoogleMap,withScriptjs } from 'react-google-maps';

export default const GoogleMapsWrapper = withScriptjs(withGoogleMap(props => {
  return <GoogleMap {...props} ref={props.onMapMounted}>{props.children}</GoogleMap>
}));

关注https://github.com/tomchentw/react-google-maps/issues/636

答案 1 :(得分:0)

您正在像这样直接突变state

this.state.eventList = requestResponse.data; //direct mutation

您永远不会像这样改变状态,因为这不是更改状态的正确方法,并且它不会重新呈现您的组件。

您必须使用setState来更改状态,这将导致重新渲染并且组件将获取数据。

this.setState({eventList : requestResponse.data})

还要确保在数据准备好后添加子组件,

{this.state.eventList.length > 0 && <GoogleApiWrapper eventList={this.state.eventList} ></GoogleApiWrapper>}