【发布时间】:2019-03-23 06:55:54
【问题描述】:
我正在使用 ReactJS 进行 Google 地图渲染。为此,我正在使用“react-google-maps”库。逻辑流程是;在页面加载时,获取用户的位置并将其绘制在地图上。 为用户提供导航链接以点击不同的 URL。为了处理导航,我使用了 React 路由器。用户的位置在 componentWillMount() 中标识,然后相应地设置状态并在 render() 中渲染地图。 问题是 render() 在完成 componentWillMount() 之前被调用,它获取空值并且失败。这种情况只发生在客户端路由中,不会出现在服务器端渲染中。
为了限制执行方式,我将 componentWillMount() 设置为异步方法,它会一直等待直到确定用户的位置。尽管如此,它还是没有帮助。
state = {
homeLocation: {},
coordinates: []
}
async componentWillMount(props) {
const { lat,lng } = await this.getcurrentLocation();
this.setState({
homeLocation:{
lat: lat,
lng: lng
}
})
}
getcurrentLocation() {
if (window.navigator && window.navigator.geolocation) {
return new Promise((resolve, reject) => {
window.navigator.geolocation.getCurrentPosition(pos => {
const coords = pos.coords;
resolve({
lat: coords.latitude,
lng: coords.longitude
});
});
});
}
return {
lat: 0,
lng: 0
};
}
render(){
<MapWithAMarker
// necessary parameters
/>
}
//Routers
const AppRouter = () => (
<Router>
<div>
<Switch>
<Route path="/" component={MapHomeLocation} exact={true}/>
<Route path="/location/:locationType" component={MapSelectedLocation}/>
<Route component={Notfound}/>
</Switch>
</div>
</Router>
);
The expected result is that coordinates should be determined first then render() should get called. In server-side routing(i.e. using anchor tags instead of <Link>) it works as expected.
【问题讨论】:
标签: javascript reactjs react-router react-google-maps