繁体   English   中英

如何通过api获取数据并使用它渲染子组件 - 对谷歌地图做出反应

[英]How fetch data by api and render child component with it - react google maps

我需要文件:eventsMapPage.js(main)和Maps.js(child)。

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
                                }}
                            />
...
```

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

我读到:

一)componentWillMount

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

通常在WPF我有绑定,这里谷歌地图的作品很奇怪。 JS应该在数据到来时自动刷新。 如何从api获得标记?

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

你是直接改变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>}

暂无
暂无

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

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