react-google-maps/api 避免在某些状态更改后重新渲染地图
react-google-maps/api Avoiding re-render of Map after some state changes
我遇到了一些问题,我的 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 经验,感谢任何帮助,谢谢!
我像这样使用 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>
</>)
除非新标记 added/removed.
,否则不会再进行不必要的刷新
我遇到了一些问题,我的 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 经验,感谢任何帮助,谢谢!
我像这样使用 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>
</>)
除非新标记 added/removed.
,否则不会再进行不必要的刷新