【问题标题】:I can print a state object array, but when I try to access a value from an object in the array, the whole object is undefined我可以打印一个状态对象数组,但是当我尝试从数组中的一个对象访问一个值时,整个对象是未定义的
【发布时间】:2020-02-20 21:56:15
【问题描述】:

我是 React 新手,正在尝试使用 google-map-react 库将标记列表添加到谷歌地图组件。

到目前为止我做了什么:

  1. 从我的 API 获取对象数据

  2. 将每个对象存储在组件状态的“标记”数组中,结构如下

[
  {
   "id":1,
   "lat":123.123,
   "lng":23.13,
   "color":"red"
   },{
   "id":11,
   "lat":53.274,
   "lng":-6.25,
   "color":"red"
  }
]

现在我正在尝试从 JSX 访问标记数组,我可以使用 this.state.markersthis.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


    【解决方案1】:

    您的数据在第一次渲染时没有被提取,所以您所拥有的只是您的默认值。

    markers 默认设置为空数组,因此您可以正常访问它。访问markers[x] 将返回 undefined 这也是可以接受的。访问markers[x].property 将 undefined 视为一个对象,它会中断。

    在尝试访问之前检查您的数据是否已完成加载。

    您可以通过有条件地渲染整个组件来做到这一点:

    if (this.state.markers.length > 0) {
      return // your components
    } else {
      return null // or whatever else you choose
    }
    

    或者您可以在访问之前检查它是否存在。

    【讨论】:

      猜你喜欢
      • 2016-06-10
      • 2020-09-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-12-15
      • 2019-12-19
      相关资源
      最近更新 更多