React-Leaflet MapContainer 未在状态更新时使用新位置值进行渲染

React-Leaflet MapContainer is not rendering with new position value on state update

我是基于 Typescript 和 Hook 的 React 应用程序的新传单用户。在我的应用程序中,应用程序使用 chrome 浏览器的地理位置 API 获取了我当前的地理位置(纬度、经度)(我已经允许浏览器的权限),并且应该显示在地图中一个标记。问题是,地图始终以初始默认位置 ([0,0]) 显示。也就是说,不显示从地理位置 API 获取的新位置更新。

问题可能很简单,但我不明白我在这里遗漏了什么,传单地图没有采用我更新的位置。我检查过,新的位置值打印正确,即使我只在简单的 div 中渲染更新的位置值,新值也正确渲染。这是我的代码如下。非常感谢任何帮助。

App.tsx

import React from 'react';
import './App.css';
import { Container } from '@material-ui/core';
import {Route,Switch} from 'react-router-dom';
import Header from './components/Header';
import SideBar from './components/SideBar';
import ShowInGoogleMap from './components/ShowInGoogleMap';
import ShowInLeafletMap from './components/ShowInLeafletMap';


function App() {
  return (
    <div className="app-div">
            <Header/>
            <div className="main-content">
              <SideBar/>
              <div className="map-content">
                <Switch>
                  <Route path="/google-map" component={ShowInGoogleMap}/>
                  <Route path="/leaflet-map" component={ShowInLeafletMap}/>
                </Switch>
              </div>  
            </div>
            

    </div>
    
    
  );
}

export default App;

###############################

ShowInLeafletMap.tsx - this is the function handling Leaflet map

import { LatLngExpression } from 'leaflet';
import React, { useState, useEffect } from 'react';
import 'leaflet/dist/leaflet.css';
import { MapContainer, Marker, Popup, TileLayer } from 'react-leaflet';

const ShowInLeafletMap = () => {
    const [position, setPosition] = useState<LatLngExpression>([0,0]);

    useEffect(() => {
      if ("geolocation" in navigator) {
        console.log("Available...");
        navigator.geolocation.getCurrentPosition(function(cPosition) {
          console.log("Latitude is :", cPosition.coords.latitude);
          console.log("Longitude is :", cPosition.coords.longitude);
          setPosition([cPosition.coords.latitude,cPosition.coords.longitude]);

        });
      } else {
        console.log("Not Available");
      }


    }, []);

    console.log('this is loaded, ', position);

return(
  
    <MapContainer center={position} zoom={13} scrollWheelZoom={false}>
    <TileLayer
      attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
      url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
    />
    <Marker position={position}>
      <Popup>
        Hi I just found Dresden
      </Popup>
    </Marker>
  </MapContainer>

    
  
)
} 

export default ShowInLeafletMap;

Here is dependency block of my package.json. I've no dev dependecies for the time being.

"dependencies": {
    "@material-ui/core": "^4.11.4",
    "@testing-library/jest-dom": "^5.11.4",
    "@testing-library/react": "^11.1.0",
    "@testing-library/user-event": "^12.1.10",
    "@types/googlemaps": "^3.43.3",
    "@types/jest": "^26.0.15",
    "@types/node": "^12.0.0",
    "@types/react": "^17.0.0",
    "@types/react-dom": "^17.0.0",
    "@types/react-leaflet": "^2.8.1",
    "@types/react-router-dom": "^5.1.7",
    "leaflet": "^1.7.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-leaflet": "^3.2.0",
    "react-router-dom": "^5.2.0",
    "react-scripts": "4.0.3",
    "typescript": "^4.1.2",
    "web-vitals": "^1.0.1"
  },

在 react-leaflet 版本 3 中,most props are immutable。至于 MapContainer 本身:

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.

您最好使用 whenCreated 属性来捕获对状态变量中基础 L.map 实例的引用,然后直接使用传单方法:

const ShowInLeafletMap = () => {

  const [map, setMap] = useState<L.Map>()

  useEffect(() => {
    if ("geolocation" in navigator && map) {
      navigator.geolocation.getCurrentPosition(function(cPosition) {
      map.panTo([cPosition.coords.latitude,cPosition.coords.longitude]);
      });
    } 
  }, [map])

  return (
    <MapContainer whenCreated(setMap)>
      ...
    </MapContainer>
  )

}

Working codesandbox