【问题标题】:Don't want to re-render even if the state is changed in react-google-maps即使在 react-google-maps 中状态发生更改,也不想重新渲染
【发布时间】:2020-07-07 22:29:46
【问题描述】:

我正在使用一个显示谷歌地图的应用程序,谷歌地图安装了多个图钉,状态通过滚动改变,活动航班根据状态改变。

当时谷歌地图的中心设置为一个activity,但是当状态改变时谷歌地图会重新渲染。我不知道如何防止渲染。

 Google Maps has NPM library。它使用 react-google-maps 并使用钩子实现。我试图用useEffect()返回false,但我没有听到它原来的样子。请告诉我

地图组件(HOC)

import React from "react";
import { withGoogleMap, GoogleMap, withScriptjs, Marker, InfoWindow } from "react-google-maps";
import { compose, withProps, withHandlers, withStateHandlers } from "recompose";

const MapWithPlaces = compose(
  withProps({
    googleMapURL:
      `https://maps.googleapis.com/maps/api/js?key=${process.env.REACT_APP_GOOGLE_PLACE_API_KEY}&libraries=geometry,drawing,places`,
    loadingElement: <div style={{ height: `100%` }} />,
    containerElement: <div style={{ height: "400px", width: "100%" }} />,
    mapElement: <div style={{ height: "100%" }} />
  }),
  withStateHandlers(
    props => ({
      infoWindows: props.places.map(p => {
        return { isOpen: false };
      }),
      defaultCenter: { 'lat': props.lat, 'lng': props.lng }
    }),
    {
      onToggleOpen: ({ infoWindows }) => selectedIndex => ({
        infoWindows: infoWindows.map((iw, i) => {
          iw.isOpen = selectedIndex === i;
          return iw;
        })
      })
    }
  ),
  withHandlers(() => {
    const refs = {
      map: undefined,
    }
    console.log(refs);

    return {
      onMapMounted: () => ref => {
        refs.map = ref
      },
      onZoomChanged: ({ onZoomChange }) => (props) => {
        const center = { 'lat': parseFloat(props.lat, 10), 'lng': parseFloat(props.lng, 10) }
        refs.map.pantTo(center)
      }
    }
  }),
  withScriptjs,
  withGoogleMap
)(props => (
  <GoogleMap defaultZoom={props.zoom} defaultCenter={props.center} key={props.key} ref={map}>
    {props.places &&
      props.places.map((place, i) => {
        let lat = parseFloat(place.lat, 10);
        let lng = parseFloat(place.lng, 10);
        return (
          <Marker
            id={place.id}
            key={place.key}
            position={{ lat: lat, lng: lng }}
            title={place.name}
            onClick={props.onToggleOpen.bind(this, i)}
            opacity={place.key === props.step ? 1 : 0.5}
            label={place.day === props.currentDay ? place.dayIndex.toString() : ''}
          >
            {props.infoWindows[i].isOpen && (
              <InfoWindow onCloseClick={props.onToggleOpen.bind(i)}>
                <div>{place.name}</div>
              </InfoWindow>
            )}
          </Marker>
        );
      })}
  </GoogleMap>
));

export default MapWithPlaces;

MapComponent(钩子)

import React, { useState, useEffect, useRef } from "react";
import { withGoogleMap, withScriptjs, GoogleMap, Marker, InfoWindow } from "react-google-maps";
// import mapStyles from "./mapStyles";

const MapCreate = React.memo((props) => {
  // const [selectedPark, setSelectedPark] = useState(null);
  const mapRef = useRef()
  useEffect(() => {
    console.log("props updates")
    console.log(props);
    const mapCenter = {
      lat: parseFloat(props.places[props.step].lat, 10),
      lng: parseFloat(props.places[props.step].lng, 10)
    }

    return false
    // refMap.current.panTo(mapCenter) //move the map to new location
  }, [props]);

  return (
    <GoogleMap defaultZoom={14} center={{ lat: props.center.lat, lng: props.center.lng }} ref={mapRef}>
      {props.places && props.places.map((place, i) => {
        let lat = parseFloat(place.lat, 10);
        let lng = parseFloat(place.lng, 10);
        return (
          <Marker
            id={place.id}
            key={place.key}
            position={{ lat: lat, lng: lng }}
            title={place.name}
            opacity={place.key === props.step ? 1 : 0.5}
            label={place.day === props.currentDay ? place.dayIndex.toString() : ''}
          >
          </Marker>
        )
      })}
    </GoogleMap>
  )
})

const MapWrapped = withScriptjs(withGoogleMap(MapCreate));

export default function Map(props) {
  const mapRef = useRef(null)
  return (
    <div style={{ width: "100%", height: "400px" }}>
      <MapWrapped
        googleMapURL={`https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=${process.env.REACT_APP_GOOGLE_PLACE_API_KEY}`}
        loadingElement={<div style={{ height: `100%` }} />}
        containerElement={<div style={{ height: "400px", width: "100%" }} />}
        mapElement={<div style={{ height: `100%` }} />}
        {...props}
      />
    </div>
  );
}

【问题讨论】:

    标签: javascript reactjs redux react-hooks react-google-maps


    【解决方案1】:

    试试#shouldcomponentupdate

    shouldComponentUpdate(nextProps, nextState)
    

    使用 shouldComponentUpdate() 让 React 知道组件的输出 不受当前状态或道具变化的影响。默认 行为是在每次状态变化时重新渲染,并且在广阔的 大多数情况下,您应该依赖默认行为。

    shouldComponentUpdate() 在渲染之前调用新道具或 正在接收状态。默认为真。不调用此方法 用于初始渲染或使用 forceUpdate() 时

    【讨论】:

      猜你喜欢
      • 2021-05-07
      • 2020-02-18
      • 2022-11-04
      • 1970-01-01
      • 2020-11-05
      • 1970-01-01
      • 2021-02-20
      • 2018-11-29
      • 1970-01-01
      相关资源
      最近更新 更多