React-Leaflet 地图不更新

React-Leaflet Map doesn't update

我的问题是 react-leaflet <MapContainer> 没有以我动态设置的位置为中心。 基本逻辑是我有一个表格,我可以在其中输入街道和门牌号,然后调用 Nominatim 并获取一些 JSON 格式的数据,从中提取建筑物的纬度和经度。 我将这些纬度和经度传递给 <MapContainer>,但它无论如何都没有响应。 使用 react-leaflet v2 时它工作得很好,但在我更新到 v3 后它停止了。

每当我设置默认位置值时,MapContainer 都会以该位置为中心。但是当我通过 Nominatim 调用动态传递另一个值时,它不起作用。

我在这里呼吁提名:

const getSearchData = async () => {
    const exampleReq = `https://nominatim.openstreetmap.org/search/${query}?format=json&building=*&addressdetails=1&limit=1&polygon_geojson=1`;
    const response = await fetch(exampleReq);
    const data = await response.json();
    // console.log(data);
    if (data === undefined || data.length === 0) {
        // array empty or does not exist
        console.log("data array is empty");
        alert("Given address unrecognized! Try again please.")
        setLatitude(DEFAULT_LATITUDE);
        setLongitude(DEFAULT_LONGITUDE);
    }else{
        setLatitude(data[0].lat);
        setLongitude(data[0].lon);
    }
};

这是我的表单提交:

<form className={style.searchForm} onSubmit={e => {
                e.preventDefault();
                setQuery(street + " " + houseNumber.replace(/\//g, "-") + ", Tallinn");
                setPosition({
                    ltd: lat, 
                    lng: long
                });

这是我的 MapBox 组件,其中包含我的传单地图:

const MapBox = (props) => {

  useEffect(()=>{
      console.log("MAPBOX!");
      console.log("updateMap() - lat ---> " + props.latitude);
      console.log("updateMap() - long ---> " + props.longitude);
      updateMap();
  },[props.street, props.houseNumber]);

  const passStreet = props.street;
  const passHouseNumber = props.houseNumber;

  const updateMap = () => {
    // console.log("updateMap() - lat ---> " + props.latitude);
    // console.log("updateMap() - long ---> " + props.longitude);
    return(
        <MapContainer center={[props.latitude, props.longitude]} zoom={20}>
            <TileLayer
                url='https://{s}.tile.osm.org/{z}/{x}/{y}.png'
                attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
            />
            <OverpassLayer street={passStreet} houseNumber={passHouseNumber} />
        </MapContainer>
      );
  }

  return(
    updateMap()
  );
}

我能够解决它。在文档中表示为:

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. The Leaflet Map instance created by the MapContainer element can be accessed by child components using one of the provided hooks or the MapConsumer component.

这段代码有助于理解:

function MyComponent() {
  const map = useMap()
  console.log('map center:', map.getCenter())
  return null
}

function MyMapComponent() {
  return (
    <MapContainer center={[50.5, 30.5]} zoom={13}>
      <MyComponent />
    </MapContainer>
  )
}

我实现了什么:

function MyComponent(props) {
const map = useMap();
map.setView(props.center, props.zoom);
return null;
}