简体   繁体   中英

Async displaying markers with React-Google-Maps and Redux

I'm trying to render markers on a Google map from a React-Redux state but I'm getting the errors "Cannot read property 'map' of undefined" and "Cannot read property '_currentElement' of null"

Here's my component:

class Map extends Component {
  constructor() {
    super()
    this.state = {}
  }

  componentDidMount() {
    APIManager.get('/api/hike', null, (err, response) => {
      if (err) {
        return
      }
      this.props.hikesReceived(response.results)
    })
  }

  componentDidUpdate() {
    console.log('updated list of hikes ' + JSON.stringify(this.props.hikes))
  }

  render() {
    const hikes = this.props.hikes.map((hike, i) => {
      const hikeMarker = {
        latlng: {
          lat: hike.location.lat,
          lng: hike.location.lng
        }
      }
      return <Markey key={i} {...hikeMarker} />
    })

    return (
      <GoogleMapLoader
        containerElement = { this.props.mapContainer }
        googleMapElement = {
          <GoogleMap
            defaultZoom={10}
            defaultCenter={this.props.center}
            options={{streetViewControl: false, mapTypeControl: false}}
            onClick={this.addMarker.bind(this)} >
             <Marker {...hikeMarker}/>
          </GoogleMap>
        } />
    )
  }
}

const stateToProps = (state) => {
  return {
    hikes: state.hike.list,
  }
}

const dispatchToProps = (dispatch) => {
  return {
    hikesReceived: (hikes) => dispatch(actions.hikesReceived(hikes)),   
  }
}

export default connect(stateToProps, dispatchToProps)(Map)

I know it's an async problem because the console.log() happens twice. The first time it's empty and the second time it renders with the data. The markers also display with no error when I'm using dummy data.

How do I go about telling the map to wait to render, or re-render, once there is data in this.props?

Half of the problem was names changing in the database. The other half was solved with:

if (this.props.hikes == null || undefined) {return: false}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM