首页 > 解决方案 > react-google-maps/api 在某些状态更改后避免重新渲染地图

问题描述

我遇到了问题,我的 GoogleMaps 实例会刷新,并且会自行以某些onClick功能为中心,在该功能上正在设置状态并且会发生整个组件渲染周期。

经过一些谷歌搜索后,建议将组件实例化分离并重新使用。现在的问题是我有一些逻辑可以在<GoogleMaps>组件内显示不再按预期工作的标记,并且我不知道如何重构:

export default function LocationSearchResults({
    ...
    }) {
    const [map, setMap] = useState(null)
    const [markersContainer, setMarkersContainer] = useState([])

    const getMap = () => {

        if (map) {
            return map;
        } else {
            setMap(<GoogleMap mapContainerStyle={containerStyle}
                options={ {
                        minZoom: 3,
                        maxZoom: 15
                    }}
                center={{
                        lat: 49.25,
                        lng: -84.5
                    }}
                zoom={5}
                onLoad={onLoad}
                onDragEnd={onDragEnd} >
                {
                    markersContainer.map(place => { //Only executes once? Does not listen for changes
                        return (< Marker key={place.id}
                            position={ place.position}
                        />
                        )
                    })

                }

                </GoogleMap>

                )

                return map

            }
        }

        render( <div className="..." >
                    {
                     getMap()
                    } 
            </div>
        )
    }

我没有大量的 React 经验,感谢任何帮助!

标签: javascriptreactjsjsxreact-google-maps

解决方案


我像这样使用设置我的组件实例化useMemo

...instantiate all event listener functions here

const map = useMemo(() =>
 {
   return (<GoogleMap
    mapContainerStyle={containerStyle}
    options={{ minZoom: 3, maxZoom: 15 }}
    center={{
      lat: 49.25,
      lng: -84.5
    }
    }
    zoom={5}
    onLoad={onLoad}
    onDragEnd={onDragEnd}
  // onUnmount={onUnmount}
  >
     {markersContainer.map(place => { return ( <Marker
                    key={place.id}
                    position={place.position} />
                    )
                   })
    }
 </GoogleMap>)

}, [markersContainer])

然后我只是在我的 render() 函数中渲染:

return (
    <>
<div>...
  {map}
</div>
</>)

除非添加/删除新标记,否则不再有不必​​要的刷新。


推荐阅读