【问题标题】:React - Google Map component not change map after re-renderReact - Google Map 组件在重新渲染后不会更改地图
【发布时间】:2017-10-23 00:32:43
【问题描述】:

我在 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 }

【问题讨论】:

    标签: javascript reactjs google-maps-api-3


    【解决方案1】:

    您已为 lnglat 设置了状态,但您没有在地图上应用它们

    => 将this.props.lat 更改为this.state.latlng 也一样:

        return <SimpleMapExampleGoogleMap
                lat={this.state.lat}
                lng={this.state.lng}
                containerElement={
                  <div style={{ height: `500px` }} />
                }
                mapElement={
                  <div style={{ height: `500px` }} />
                }
            />
    

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

      constructors(props){/*...*/}
    
      componentWillReceiveProps(nextProps) {
        this.setState({
          lat: nextProps.lat,
          lng: nextProps.lng,
        });
      }
    
      render(){/*...*/}
    

    如有错误请在此留言,谢谢

    【讨论】:

    • 非常非常感谢 * 100 :) 它有效,天哪,我没想到 componentWillReceiveProps 你让我开心了 :) P.S 没有错误 :)
    • 不客气,很高兴你成功了^^!有关 ReactJS 或 Google/Leaflet 地图的更多问题,请随时联系我!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2021-05-19
    • 2022-01-26
    • 1970-01-01
    • 2018-03-17
    相关资源
    最近更新 更多