我正在获取用户的位置并将其设置为“onSuccess”函数的新状态, 该组件不会重新渲染。 经过大量检查后,我发现 React 并不将其视为状态更改,因为在这种情况下它是一个数组,并且它没有通过 React 的“相等”检查作为已更改的状态。 就这样,我尝试过的一切都不起作用。有什么想法吗?
import { useEffect, useState } from "react";
import { MapContainer, TileLayer, Marker, Popup } from "react-leaflet";
export default function Map() {
const [location, setLocation] = useState([52.234, 13.413]);
const onSuccess = (position) => {
let userLocation = [position.coords.latitude, position.coords.longitude];
setLocation([...userLocation]);
};
useEffect(() => {
if (!("geolocation" in navigator)) {
alert("no Geolocation available");
}
navigator.geolocation.getCurrentPosition(onSuccess);
}, []);
console.log(location);
return (
<>
<MapContainer
className="leaflet-map"
center={location}
zoom={11}
scrollWheelZoom={false}
>
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<Marker position={[51.505, -0.09]}>
<Popup>
A pretty CSS3 popup. <br /> Easily customizable.
</Popup>
</Marker>
</MapContainer>
</>
);
}
最佳答案
即使按照文档中所述更改了 center
属性,MapContainer
在安装后也不会重新定位:
https://react-leaflet.js.org/docs/api-map
Except for its children, MapContainer props are immutable: changing them after they have been set a first time will have no effect on the Map instance or its container.
您可以通过传递 key
属性来强制替换 MapContainer
,每当 location
发生变化时您都会更改该属性,例如:
<MapContainer
key={`${location[0]}-${location[1]}`}
或者研究 react-leaflet
中的其他选项,例如 useMap
来访问 Leaflet Map 实例并调用 map.setView(...)
https://leafletjs.com/reference-1.7.1.html#map-setview
关于reactjs - setState 不会重新渲染 React 功能组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65469479/