React-Leaflet 总是使用“MouseMove”重绘地图

问题描述 投票:0回答:1

我想当鼠标在我的 React 应用程序中移动时显示地理坐标。我注意到,通过“Mousemove”,地图会重复重绘所有数量较多的对象。我怎样才能防止这种情况并只更新坐标?

这是代码:

export class MapView extends Component {

state = {
lat: 10,
lon: 50,
tileName: "",
tiles: [],
};

MouseMove = () => {
const map = useMapEvent("mousemove", (e) => {
  let lon = e.latlng.lng;
  let lat = e.latlng.lat;

  this.setState({
    lat: lat.toFixed(6),
    lon: lon.toFixed(6),
    tileName: this.getTileNameSRTM(lon, lat),
  });
});
};

render() {
let self = this;
const matrix = this.props.matrix;

function renderMatrix() {
  if (matrix !== null) {
    return (
      <div>
        <Rectangle bounds={matrix.rect} pathOptions={{ color: "Blue" }} />
      </div>
    );
  }
}

function Zoom() {
  const map = useMapEvent("zoom", (e) => {
    console.log("zoom");
    self.drawTile(map, self);
  });
  return self.state.tiles;
}

function Pan() {
  const map = useMapEvent("move", (e) => {
    console.log("pan");
    //self.drawTile(map, self);
  });
  return self.state.tiles;
}

return (
  <div
    className="w3-col w3-margin-left w3-margin-right"
    style={{ width: "calc(80% - 2*16px)" }}
  >
    <div className="w3-container w3-blue w3-margin-top w3-margin-bottom w3-padding">
      <FontAwesomeIcon icon="fa-solid fa-map" className="w3-margin-right" />
      Map Viewer Latitude: {this.state.lat} Longitude: {this.state.lon}{" "}
      <label className="w3-right">{this.state.tileName}</label>
    </div>
    <MapContainer
      center={[50.65935313570456, 10.665137544640139]}
      zoom={5}
      style={{ height: "calc(100vh - 157.48px - 31px - 5*16px)" }}
      scrollWheelZoom={true}
    >
      <TileLayer
        attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <this.MouseMove />
      <Zoom />
      <Pan />
    </MapContainer>
  </div>
 );
 }
}

export default MapView;

源代码不完整,我只发布了受影响的部分。

javascript reactjs react-leaflet
1个回答
0
投票

使用react memo跳过react中的重新渲染 https://react.dev/reference/react/memo 用备忘录包裹你的地图组件

export defaultmemo(MapView)
© www.soinside.com 2019 - 2024. All rights reserved.