我正在嘗試對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
你的代碼的哪部分是異步的?有很多谷歌地圖調用,並不清楚它是否是其中之一,或其他。 –