javascript - 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 经验,感谢任何帮助!
解决方案
我像这样使用设置我的组件实例化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>
</>)
除非添加/删除新标记,否则不再有不必要的刷新。
推荐阅读
- java - 在Java中将UTC时间戳转换为带有偏移量的时间
- pysnmp - 没有 securityEngineId 的 pysnmp 接收器
- node.js - Youtube PubSubHubbub 在我的回调中没有收到发帖请求
- python - ReLU 与 Sigmoid 的关系
- sql - 在雪花中查询小于/大于值
- sql - 如何在 TDengine 上查看查询状态?
- c++ - 有什么方法可以避免在没有命名空间污染的情况下在标头中完全指定的类名?
- c++ - 使另一个类的指针指向“this”
- java - Java中的REGEX用于提取字符串中的连续重复字符
- python - 为什么使用列标题名称很好但不能使用列索引