【问题标题】:Async displaying markers with React-Google-Maps and Redux使用 React-Google-Maps 和 Redux 异步显示标记
【发布时间】:2017-02-02 15:15:35
【问题描述】:

我正在尝试从 React-Redux 状态在 Google 地图上呈现标记,但我收到错误“无法读取未定义的属性 'map'”和“无法读取 null 的属性 '_currentElement'”

这是我的组件:

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)

我知道这是一个异步问题,因为 console.log() 发生了两次。第一次是空的,第二次用数据渲染。当我使用虚拟数据时,标记也不会出现错误。

一旦 this.props 中有数据,我该如何告诉地图等待渲染或重新渲染?

【问题讨论】:

  • 你可以检查 undefined/empty data/null 或其他什么,然后返回 false
  • 我已经尝试过“if (this.props.hikes == null || undefined) {return: false}”,它只会呈现两次错误
  • 实际上,“假”有效。前后端之间存在变量命名问题。谢谢@elsololobo!

标签: google-maps reactjs react-redux


【解决方案1】:

问题的一半是数据库中的名称更改。另一半解决了:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-07
    • 2020-02-17
    • 2014-02-13
    • 2021-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    相关资源
    最近更新 更多