在 React JS 中传递纬度和经度作为道具的最佳方式

Best way to pass latitude and longitude as props in react js

我想在我的应用程序中包含特定地理位置的 google 地图。位置可以更改,因此不能硬编码。

我的地图组件如下(去掉无关内容):

import React from 'react';

class Map extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      lat: this.props.selectedVenue.lat,
      lng: this.props.selectedVenue.lng,
      zoom: 13,
      maptype: 'Satellite”',      
    }
  }

  componentDidMount() {
    let map = new window.google.maps.Map(document.getElementById('map'), {
      center: {lat: this.state.lat, lng: this.state.lng },
      zoom: 13,
      mapTypeId: 'roadmap',
    });

  }

  render() {
    console.log("this.props.selectedVenue.lat", this.props.selectedVenue.lat);
    console.log("this.props.selectedVenue.lng", this.props.selectedVenue.lng);    
    return (
      <div id='app'>
        <div id='map' />
      </div>
    ); 
  } 
}

export default Map; 

当我将值硬编码为 Map.js 状态时,一切正常,地图出现。但是,当我使用上述方法时,我得到的是一张空白地图。这些值正在通过,但控制台告诉我:

"InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number"

我试过使用 Number() 来确保它实际上是一个数字,Math.round 来确保它与位数无关,并尝试完全绕过状态并只传递 prop直接进入但没有运气。我试过在这里搜索,但是在提出问题的地方没有任何令人满意的答案(如果我在这方面有误,很高兴得到纠正)。

知道我哪里出错了吗?

谢谢

*编辑/补充*

this.props.selectedVenue原本是在搜索会场时在祖父组件(App.js)的状态下设置的。返回的场地选择存储在状态中:

  constructor(props) {
    super(props);

this.state = {
  ...
  venues : [],
  selectedVenue : []
  ...
}

this.search = this.search.bind(this);
this.populateSelectedVenue = this.populateSelectedVenue.bind(this);

}

  search(term) { 
    this.setState({
      ...
      venues : [],
      selectedVenue : [],
      ...
    })

    APIVenues.getVenues(term).then(res => { // getVenues
      this.setState({venues: res});
    });
  } 

另一种方法是用合适的地点设置this.state.selectedVenues:

  populateSelectedVenue = (venue) => { concat
    this.setState({selectedVenue: venue});
  } 

populateSelectedVenue 作为道具传递给另一个组件,它由 onClick 触发,并将适当的地点传递给它。

您需要在 Map 组件中使用 componentWillReceiveProps 生命周期方法。每次 传递给您的组件的所有道具发生变化时,都会 调用此方法。

所以,解决方案是:

  1. componentDidMount生命周期方法中,新建一个google地图对象,使用状态值default经纬度,并设置新的map 上面的对象作为Map组件中的成员变量,只是为了保持对象的引用。

    componentDidMount() { this.map = new window.google.maps.Map(document.getElementById('map'), { center: { lat: this.state.lat, lng: this.state.lng }, zoom: 13, mapTypeId: 'roadmap', }); }

  2. componentWillReceiveProps(nextProps)生命周期方法中,使用nextProps参数设置地图中心。

    componentWillReceiveProps(nextProps) { if (nextProps.selectedVenue.lat !== this.props.selectedVenue.lat || nextProps.selectedVenue.lng !== this.props.selectedVenue.lng) { this.map.setCenter({lat: nextProps.selectedVenue.lat, lng: nextProps.selectedVenue.lng}); } }