我必须文件: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)componentWillMountb) 谷歌地图上的事件,如 onChange 或 onBoundsChanged,但我不知道如何在我的项目中使用它。通常在 WPF 中我有绑定,这里谷歌地图工作很奇怪。JS 应该在数据来的时候自动刷新。如何从api获得标记?
2 回答

白猪掌柜的
TA贡献1893条经验 获得超10个赞
你直接变异之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>}
添加回答
举报
0/150
提交
取消