我正在尝试对componentWillMount方法中的API执行异步调用。事实上,我希望render
方法在componentWillMount方法后执行,因为我需要将props
传递给我的render
方法中的组件。componentWillMount中的异步调用在渲染方法后完成
这里是我的代码:
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调用之后组件将被渲染。 – Rowland
你的代码的哪部分是异步的?有很多谷歌地图调用,并不清楚它是否是其中之一,或其他。 –