ReactJS编译失败:“对象”未定义为no-undef

时间:2017-11-30 20:24:00

标签: javascript reactjs google-maps

有人可以帮我解决代码中缺少的内容吗?我试图这样做几个小时并且错误后出错......

目标是将所有对象坐标提取到GoogleMaps Markers ...

(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

任何提示都将受到赞赏。非常感谢!

2 个答案:

答案 0 :(得分:1)

这是错误的:

d1 <- data.frame(a=rnorm(5), b=1:5, c=rnorm(5))
d2 <- data.frame(a=1:5, b=rnorm(5), c =rnorm(5))
d3 <- data.frame(a=1:5, b=rnorm(5), c= rnorm(1:5))

my_test_data <- rbind(d1, d2, d3)

m <- lm(a ~ b, data = my_test_data)
plot(a ~ b, data = my_test_data)
abline(m)

因为您正在映射this.state.Objects.location.coordinates,并且您正在使用索引来访问 Objects [i] .location.coodinates [0] Objects [ i] .location.coordinates [1] 对象并未在任何地方定义,但是this.state.Objects是。

我猜你的意思是这样的:

{this.state.Objects.location.coordinates.map((item, i) => (
    <Marker position= {{ lat: Objects[i].location.coodinates[0], lng: Objects[i].location.coordinates[1] }}/>
))}

以下是如何为每个对象列出Lat / Long的示例:http://jsfiddle.net/g4hr5jnc/

您只需将其替换为Google地图组件

即可

答案 1 :(得分:0)

我认为问题是代码首先运行constructor(props),然后运行render()然后运行componentDidMount()。因此,当您运行render()时,this.state.Objects仍然是一个空数组 你可能想尝试:
1.将componentDidMount()中的任何内容写入constructor(props)
2.将componentDidMount()更改为componentWillMount()

更多关于反应组件生命周期的信息:
http://busypeoples.github.io/post/react-component-lifecycle/