问题描述
我遇到了一些问题,我的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>
</>)
除非添加/删除了新标记,否则不再进行不必要的刷新。