【发布时间】:2020-02-20 21:56:15
【问题描述】:
我是 React 新手,正在尝试使用 google-map-react 库将标记列表添加到谷歌地图组件。
到目前为止我做了什么:
从我的 API 获取对象数据
将每个对象存储在组件状态的“标记”数组中,结构如下
[
{
"id":1,
"lat":123.123,
"lng":23.13,
"color":"red"
},{
"id":11,
"lat":53.274,
"lng":-6.25,
"color":"red"
}
]
现在我正在尝试从 JSX 访问标记数组,我可以使用 this.state.markers 或 this.state.markers[0] 很好地访问它,但是每当我尝试使用 this.state.markers[0].id 访问存储在数组对象之一中的值时,显示为undefined。
这里this.state.markers[1] 工作正常
取消注释 this.state.markers[1].id 会破坏它
显示状态值的 React 开发工具
完整代码:
class GoogleMap extends Component {
static defaultProps = {
center: {
lat: 53.35,
lng: -6.26
},
zoom: 13,
};
state = {
markers: [
]
};
async componentDidMount(){
const url = "/api/crime/all";
const response = await fetch(url);
const data = await response.json();
console.log(data)
//Create a copy of the current markers array
var newMarkers = this.state.markers.slice();
for(var i = 0; i < data.length ; i++){
console.log(data[i].id)
var marker = {
id: data[i].id,
lat: data[i].latitude,
lng: data[i].longitude,
color: "red"
}
//Push each object to the array
newMarkers.push(marker);
}
// Update the state with the new array
this.setState({markers: newMarkers});
}
render() {
return (
// Important! Always set the container height explicitly
<div style={{ height: '100vh', width: '100%' }}>
<GoogleMapReact
bootstrapURLKeys={{ key: "AIzaSyA7qsNPuWR4K4RncWMv1sFfxUIJG-7zOh0" }}
defaultCenter={this.props.center}
defaultZoom={this.props.zoom}
options={createMapOptions}
>
{/* Here Im trying to access the array from the jsx */}
{console.log("Markers "+ JSON.stringify(this.state.markers))}
{console.log("Markers[0] "+ JSON.stringify(this.state.markers[0]))}
{console.log("Markers[1] "+ JSON.stringify(this.state.markers[1]))}
/*The below line is what causes the error (Cannot access id of undefined)*/
{/* {console.log("Markers[1].id "+ JSON.stringify(this.state.markers[1].id))} */}
{/* Some hardcoded Markers for now */}
<Marker
id={1}
lat={53.352}
lng={-6.264}
color="green"
/>
<Marker
id={2}
lat={53.3512}
lng={-6.26234}
color="red"
/>
<Marker
id={3}
lat={53.354}
lng={-6.2632}
color="orange"
/>
</GoogleMapReact>
</div>
);
}
}
export default GoogleMap;
提前感谢您的帮助!
【问题讨论】:
标签: javascript reactjs jsx