在react js中传递纬度和经度作为道具的最佳方式



我正试图在我的应用程序中包含某个地理位置的谷歌地图。位置可以更改,因此不能硬编码。

我的地图组件如下(删除无关内容(:

import React from 'react';
class Map extends React.Component {
constructor(props) {
super(props);
this.state = {
lat: this.props.selectedVenue.lat,
lng: this.props.selectedVenue.lng,
zoom: 13,
maptype: 'Satellite”',      
}
}
componentDidMount() {
let map = new window.google.maps.Map(document.getElementById('map'), {
center: {lat: this.state.lat, lng: this.state.lng },
zoom: 13,
mapTypeId: 'roadmap',
});
}
render() {
console.log("this.props.selectedVenue.lat", this.props.selectedVenue.lat);
console.log("this.props.selectedVenue.lng", this.props.selectedVenue.lng);    
return (
<div id='app'>
<div id='map' />
</div>
); 
} 
}
export default Map; 

当我将值硬编码到Map.js状态时,一切都很好,地图就会出现。然而,当我使用上面的方法时,我会得到一张空白的地图。数值正在通过,但控制台告诉我:

"InvalidValueError:setCenter:不是LatLng或LatLngLiteral:属性lat:不是数字">

我尝试过使用Number((来确保它实际上是一个数字,Math.round来确保它与数字的数量无关,并尝试过完全绕过状态,直接传递道具,但没有成功。我试着在这里搜索,但在提出问题的地方没有任何令人满意的答案(如果我错了,很乐意得到纠正(。

知道我哪里错了吗?

感谢

*编辑/附加*

this.props.selectedVenue最初在搜索场地时设置为祖父母组件(App.js(的状态。返回的场馆选择存储在状态:

constructor(props) {
super(props);
this.state = {
...
venues : [],
selectedVenue : []
...
}
this.search = this.search.bind(this);
this.populateSelectedVenue = this.populateSelectedVenue.bind(this);

}

search(term) { 
this.setState({
...
venues : [],
selectedVenue : [],
...
})
APIVenues.getVenues(term).then(res => { // getVenues
this.setState({venues: res});
});
} 

另一种方法用于设置这个.state.selectedVenues与合适的场地:

populateSelectedVenue = (venue) => { concat
this.setState({selectedVenue: venue});
} 

populateSelectedVenue作为道具传递给另一个组件,在那里它由onClick触发,并将适当的场地传递给它。

您需要在Map组件中使用componentWillReceiveProps生命周期方法。每当传递给组件的所有道具都发生更改时,就会调用此方法。

因此,解决方案是:

  1. componentDidMount生命周期方法中,使用state值新建一个具有default纬度和经度的google映射对象,并将上面的新map对象设置为Map组件中的成员变量,仅用于保留对象的引用。

    componentDidMount() { this.map = new window.google.maps.Map(document.getElementById('map'), { center: { lat: this.state.lat, lng: this.state.lng }, zoom: 13, mapTypeId: 'roadmap', }); }

  2. componentWillReceiveProps(nextProps)生命周期方法中,使用nextProps参数设置地图中心。

    componentWillReceiveProps(nextProps) { if (nextProps.selectedVenue.lat !== this.props.selectedVenue.lat || nextProps.selectedVenue.lng !== this.props.selectedVenue.lng) { this.map.setCenter({lat: nextProps.selectedVenue.lat, lng: nextProps.selectedVenue.lng}); } }

最新更新