[英]react-google-maps/api Avoiding re-render of Map after some state changes
I was having problems where my GoogleMaps instance would refresh and self center itself on some onClick
function where the state was being set and the entire Component rendering cycle would happen.我遇到了问题,我的 GoogleMaps 实例会刷新并自我集中在某个
onClick
函数上,在该函数上设置了状态并且整个组件渲染周期都会发生。
After some Googling it was suggested that the component instantiation be separated and re-used.经过一些谷歌搜索后,建议将组件实例化分离并重新使用。 The problem now is I have some logic to display markers inside
<GoogleMaps>
component that is no longer working as expected and I don't know how to refactor:现在的问题是我有一些逻辑可以在
<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>
)
}
I don't have a ton of experience with React, any help is appreciated thanks!我没有大量的 React 经验,感谢您的帮助!
I set up my component instantiation like so using useMemo
我使用
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])
then I simply render in my render() function:然后我只是在我的 render() 函数中渲染:
return (
<>
<div>...
{map}
</div>
</>)
No more unnecessary refreshes unless new markers are added/removed.除非添加/删除新标记,否则不再进行不必要的刷新。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.