当通过道具时,react-google-maps地图未更新,并且标记在更新时位于后面一个位置

时间:2019-04-11 01:31:37

标签: reactjs redux react-google-maps

地图加载时我可以使用它,但是每当我通过道具时,地图本身就不会改变。

标记会更改,但始终比应显示的状态晚1状态,这显然是同步问题,但我不确定如何在组件中解决此问题。

class Map extends React.Component {
  state = {
     center: { lat: 50.937531, lng: 6.960278600000038 }
  }

  componentWillReceiveProps = () => {
    this.setState({
      center: { 
        lat: Number(parseFloat(this.props.city.lat)),
        lng: Number(parseFloat(this.props.city.lng))
      }
    });
  }

  render() {
    console.log(this.state.center)
    return (
      <div>
        <MapDetails
          googleMapURL="https://maps.googleapis.com/maps/api/js?key=AIzaSyB-L-IikkM6BZ_3Z2QIzbkx4pdAkP76tok&v=3.exp&libraries=geometry,drawing,places"
          loadingElement={<div style={{ height: `100%` }} />}
          containerElement={<div style={{ height: `100vh`}} />}
          mapElement={<div style={{ height: `100%` }} />}
          mapCenter={this.state.center}
        />
      </div>
    )
  }
}

const mapStateToProps = (state) => {
  return { city: state.CityNameReducer }
}

export default connect(mapStateToProps)(Map);

const MapDetails = withScriptjs(withGoogleMap(props =>
  <GoogleMap
    defaultZoom={12}
    defaultCenter={props.mapCenter}
  >
    <Marker
      position={props.mapCenter}
    />
  </GoogleMap>
));

我最大的问题是为什么地图本身没有更新?

2 个答案:

答案 0 :(得分:0)

向GoogleMap组件添加密钥。每次提供的密钥均应唯一。为了进行测试,请使用新的Date()。getTime()函数。

<GoogleMap key={new Date().getTime()}/>

正如我提到的,它仅用于测试,因此请确保以更好的方式提供此密钥

答案 1 :(得分:-1)

我建议您使用shouldComponentUpdate(nextProps,nextState){}代替componentWillReceiveProps()。

我建议您阅读以下页面,以了解其工作原理。 Updating and componentWillReceiveProps

我没有更多有关组件父级中发生的情况的信息,因此我无法更深入地探讨问题。但是我认为您可以通过更改解决方案来获得解决方案。