有人可以帮我看看我的代码中缺少什么吗?我尝试这样做几个小时,然后错误接连出现......
目标是将所有对象坐标提取到 GoogleMaps 标记中...
(reactJS 新手)
class maps extends Component{
constructor(props){
super(props)
this.state = { Objects: [] }
}
render(){
{this.state.Objects.location.coordinates.map((item, i) => (
<Marker position= {{ lat: Objects[i].location.coodinates[0], lng: Objects[i].location.coordinates[1] }}/>
))}
const MyMapComponent = withScriptjs(withGoogleMap((props) =>
<GoogleMap
defaultZoom={2}
defaultCenter={{ lat: 40.6333333, lng: -8.65 }}
>
</GoogleMap>
))
return(
<div>
<MyMapComponent
isMarkerShown
googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyCnQmNcHpzoytzm02Zf-inD6xxTdSRJdLg&v=3.exp&libraries=geometry,drawing,places"
loadingElement={<div style={{ height: `100%` }} />}
containerElement={<div style={{ height: `400px` }} />}
mapElement={<div style={{ height: `100%` }} />}
/>
</div>
)
}
componentDidMount(){
axios.get('https://api.ost.pt/traffic_events/?key=VMSBvXtmOixXVuaHqeyAxDEhQkbnJpXZBYjDufEu').then( response => {
const { Objects } = response.data
console.log(Objects)
this.setState({Objects})
})
.catch(error => {
console.log('Error fetching and parsing data', error);
});
}
These are the objects.coordinates from api data that I need to fetch
任何提示将不胜感激。非常感谢!
最佳答案
这是错误的:
{this.state.Objects.location.coordinates.map((item, i) => (
<Marker position= {{ lat: Objects[i].location.coodinates[0], lng: Objects[i].location.coordinates[1] }}/>
))}
因为您正在映射 this.state.Objects.location.coordinates,并且您正在使用索引访问 Objects[i].location.coordinates[0] 和 Objects[ i].location.coordinates[1],并且 Objects 未在任何地方定义,但 this.state.Objects 是。
我猜你的意思是这样的:
{this.state.Objects.map((item, i) => (
<Marker position= {{ lat: item.location.coodinates[0], lng: item.location.coordinates[1] }}/>
))}
这是一个如何列出每个对象的纬度/经度的示例:http://jsfiddle.net/g4hr5jnc/
您只需将其替换为 Google map 组件
关于javascript - ReactJS 编译失败 : 'Objects' is not defined no-undef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47581967/