React - Google地图组件在重新渲染后不会更改地图

Aga*_*ata 2 javascript google-maps-api-3 reactjs

我在React中遇到了Google Map的问题.一切都很好但是,当我尝试在这张地图中重新渲染其他地方时它不起作用:(我的意思是当我改变城市(例如选择)时使用新的道具(纬度,经度),但城市一地图不改变

import React from 'react';
import ReactDOM from 'react-dom';
import { withGoogleMap, GoogleMap, Marker } from "react-google-maps";

const SimpleMapExampleGoogleMap = withGoogleMap( props => {
    console.log("here new props are used", props)
    return <GoogleMap
      defaultZoom={15}
      defaultCenter={new google.maps.LatLng(props.lat, props.lng)}
    />
 }
);

class GMap extends React.Component{
    constructor(props) {
        super(props);
        this.state = {
            lat: this.props.lat,
            lng: this.props.lng
        }
    }

    render() {
        console.log("New props ", this.props)

        return <SimpleMapExampleGoogleMap
                lat={this.props.lat}
                lng={this.props.lng}
                containerElement={
                  <div style={{ height: `500px` }} />
                }
                mapElement={
                  <div style={{ height: `500px` }} />
                }
            />
    }
}
export { GMap }
Run Code Online (Sandbox Code Playgroud)

thi*_*108 6

您已为状态设置lng,lat但未在地图上应用它们

=>更改this.props.latthis.state.lat,并且相同lng:

    return <SimpleMapExampleGoogleMap
            lat={this.state.lat}
            lng={this.state.lng}
            containerElement={
              <div style={{ height: `500px` }} />
            }
            mapElement={
              <div style={{ height: `500px` }} />
            }
        />
Run Code Online (Sandbox Code Playgroud)

如果上面的代码还没有更新你的地图,那么随意添加以下方法(与构造函数相同的级别):

  constructors(props){/*...*/}

  componentWillReceiveProps(nextProps) {
    this.setState({
      lat: nextProps.lat,
      lng: nextProps.lng,
    });
  }

  render(){/*...*/}
Run Code Online (Sandbox Code Playgroud)

如果您有错误,也请在此发帖,谢谢