我最近开始使用 React.js,并正在使用 React-Leaflet-js 开发一个项目。我的问题是,每当更新以下代码中的
MapContainer
变量时,我的 center
不会更改页面的 position
:
...
render() {
const position = [this.state.location.lat, this.state.location.lng];
return (
<MapContainer
className="map"
center={position}
zoom={this.state.zoom}
scrollWheelZoom={true}>
...
供参考,正在更新的
state
变量如下所示:
state = {
location: {
lat: 40.7128,
lng: -74.0060,
},
haveUsersLocation: false,
zoom: 13,
}
奇怪的是,当
marker
变量更改时,position
设置为 {position}
的 position
会自动更新,但 center
的 MapContainer
不会更新。我不确定为什么 map
没有响应并调整其 center
。
注意:我尝试查看this,但它没有回答我的问题。请帮忙。
center
属性只是初始化地图,如果您想更新实际显示的地图中心,则必须使用setView
或flyTo
(如果您想要平滑的动画)。为了获得 Leaflet Map 参考,您需要使用钩子 useMap
。
function FlyMapTo() {
const map = useMap()
useEffect(() => {
map.flyTo(position)
}, [position])
return null
}
return (
<MapContainer
className="map"
center={position}
zoom={this.state.zoom}
scrollWheelZoom={true}>
<FlyMapTo />
</MapContainer>
)