【发布时间】:2018-07-11 12:05:00
【问题描述】:
我正在尝试在我的应用中包含某个地理位置的谷歌地图。位置可以更改,因此不能硬编码。
我的地图组件如下(不相关的东西被删除):
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: not a LatLng or LatLngLiteral: in property lat: not a number"
我尝试使用 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});
});
}
另一种方法是使用适当的场地设置 this.state.selectedVenues:
populateSelectedVenue = (venue) => { concat
this.setState({selectedVenue: venue});
}
populateSelectedVenue 作为 prop 传递给另一个组件,在该组件中由 onClick 触发,并将适当的场所传递给它。
【问题讨论】:
-
如果你在 componentDidMount()
console.log({lat: this.state.lat, lng: this.state.lng })987654325@ 的开头添加以下日志,你会在控制台看到什么 -
刚刚编辑了这个问题,因为我错过了一些东西。控制台说:“InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number”。 selectedVenue 作为父组件的 props 传递,包含所有场地详细信息,包括 lat 和 lng。
-
在创建
Map时是否加载了传入Map的selectedVenue?可能是selectedVenue是异步加载的,而您的构造函数没有得到正确的值。 -
你能注释掉 let map = ..... 块并在 componentDidMount 中记录
console.log({lat: this.state.lat, lng: this.state.lng })。然后你会看到哪里出了问题。 -
Chathura:按照建议添加 console.log 会返回:Object { lat: undefined, lng: undefined } Tholle:可能是这样......但不知道如何补救。也许是一个 setState?
标签: javascript reactjs google-maps google-maps-api-3 react-props