【发布时间】:2017-04-09 21:40:02
【问题描述】:
我正在尝试在 componentWillMount 方法中对 API 执行异步调用。实际上,我希望在 componentWillMount 方法之后执行 render 方法,因为我需要将 props 传递给我的 render 方法中的组件。
这是我的代码:
class TennisSearchResultsContainer extends React.Component {
componentWillMount () {
// TODO: Build markers for the map
// TODO: Check courtsResults object and database for tennis court
this.courtsMarkers = this.props.courtsResults.map((court) => {
return new google.maps.Marker({
position: new google.maps.LatLng(JSON.parse(court.LOC).coordinates[1], JSON.parse(court.LOC).coordinates[0]),
title: court.NAME,
animation: google.maps.Animation.DROP
});
});
}
render () {
return <TennisSearchResults criterias={this.props.criterias} courtsMarkers={this.courtsMarkers} />;
}
}
我不明白为什么我的渲染方法似乎不等待异步调用完成并将未定义的道具传递给我的子组件...
我说的对吗?我应该怎么做才能解决这个问题?有什么办法处理呢?
【问题讨论】:
-
你需要使用
componentDidMount,因为componentWillMount在组件被挂载到DOM之前只运行一次。因此,不能保证组件会在 AJAX 调用之后呈现。 -
你的代码的哪一部分是异步的?有很多谷歌地图调用,不清楚是其中一个,还是其他什么。
标签: javascript reactjs asynchronous