猿问

如何通过 api 获取数据并用它呈现子组件 - 反应谷歌地图

我必须文件: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 中获取。所以我的地图上没有任何标记。


我读到:


a)componentWillMount


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


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


海绵宝宝撒
浏览 117回答 2
2回答

白猪掌柜的

你直接变异之state类的,this.state.eventList&nbsp;=&nbsp;requestResponse.data;&nbsp;//direct&nbsp;mutation你永远不会像这样改变状态,因为这不是改变状态的正确方法,它不会重新渲染你的组件。您必须使用setState来更改您的状态,这将导致重新渲染并且您的组件将获取数据。this.setState({eventList&nbsp;:&nbsp;requestResponse.data})还要确保在数据准备好时添加子组件,{this.state.eventList.length&nbsp;>&nbsp;0&nbsp;&&&nbsp;<GoogleApiWrapper&nbsp;eventList={this.state.eventList}&nbsp;></GoogleApiWrapper>}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答