【问题标题】:Google Map keeps re-rendering even if render() is not called即使未调用 render(),谷歌地图也会继续重新渲染
【发布时间】:2018-03-19 03:18:17
【问题描述】:

我目前正在使用 reactjs 和 redux 将谷歌地图导入我的项目。

但是每当我点击标记或只是放大时,整个地图都会重新渲染 并且地图变灰并使用相同的标记重新绘制相同的地图。

我尝试过使用 shouldComponentUpdate,它成功停止了正在调用的 render() 函数,但地图仍在重新渲染!

被点击时标记的事件监听器

window.google.maps.event.addListener(marker, 'click', ()=>{
  this.props.dispatch(Map.showChatroom(id, title));
});

应该组件更新:

  shouldComponentUpdate(nextProps, nextState){
    if(this.props.map.location.lat === nextProps.map.location.lat){
      return false
    }else{
      return true
    }
  }

渲染():

  render() {
    const {map} = this.props;
    return (
      <React.Fragment>
        {
          map.activeChatroom.id != null &&
            <Chatroom id={map.activeChatroom.id} title={map.activeChatroom.title} />
        }
        <GoogleMap map={map} getPostion={this.getPostion.bind(this)}/>
      </React.Fragment>
    );
  }

谷歌地图:

const GoogleMap = function(props){
  return (
        <div className="map">
          <div className='map__state'>
              Zoom level: {props.map.map.zoom}<br />
              Map type: {props.map.map.maptype}<br />
              Latitude: {props.map.location.lat}<br />
              Longtitude: {props.map.location.lng}<br />
              Place: {props.map.location.place_formatted}<br />
              Place ID: {props.map.location.place_id}<br />
              Location: {props.map.location.place_location}<br />
              <button className="map__state__positioningBtn" onClick={props.getPostion}>Positioning</button>
          </div>
          <input className='pac_input' type='text' placeholder='Enter a location' />
          <div className='map__container' />;

        </div>
        );
}

map__container 类是 google 地图的渲染位置

演示:https://hello-neighbor.github.io/Hello-Neighbor-Chat/

源代码:https://github.com/Hello-Neighbor/Hello-Neighbor-Chat

非常感谢任何答案或建议

【问题讨论】:

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


    【解决方案1】:

    基于文档shouldComponentUpdate 不会阻止重新渲染子组件 (https://reactjs.org/docs/react-component.html#shouldcomponentupdate)。

    返回 false 不会阻止子组件在其状态更改时重新渲染。

    目前,如果 shouldComponentUpdate() 返回 false,则不会调用 componentWillUpdate()、render() 和 componentDidUpdate()。请注意,未来 React 可能会将 shouldComponentUpdate() 视为提示而不是严格指令,返回 false 仍可能导致组件重新渲染。

    在此处查看如何更好地组织您的 Google 地图代码:https://www.fullstackreact.com/articles/how-to-write-a-google-maps-react-component/。

    希望它会有所帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多