javascript - 动态边界更改不会在 'react-leaflet' 中产生任何影响

标签 javascript reactjs leaflet react-leaflet fitbounds

我在尝试使用 react-leafletbounds 属性时遇到了问题。 我的用例是我的应用程序在状态中定义了一些初始边界(比方说,后备边界),并且这些边界在组件的第一次渲染期间传递。应用程序架构要求我发送请求以在组件内设置新边界,问题就来了。

在下面的示例中(我使用 setTimeout 模拟了 AJAX 请求)我们可以注意到超时后来自请求的新边界根本没有设置,我也没有很清楚为什么会这样。

我怀疑是动画的问题,因为当增加超时延迟时,问题没有发生,并且第二个边界设置正确。

我的设置:

"react": "17.0.0"
"leaflet": "1.6.0"
"react-leaflet": "2.7.0"
import React, { useState } from "react";
import { Map, ZoomControl, TileLayer } from "react-leaflet";

import "./styles.css";
import "leaflet/dist/leaflet.css";

export default function App() {
  const [bounds, setBounds] = useState([
    [75, -25],
    [30, 45]
  ]);

  setTimeout(() => {
    setBounds([
      [59.569068610511465, 10.387057922780514],
      [59.565111563593824, 10.397184267640114]
    ]);
  }, 200);

  return (
    <Map
      bounds={bounds}
      maxBounds={bounds}
      zoomControl={false}
      style={{
        height: 400,
        width: 400
      }}
    >
      <TileLayer
        url="//{s}.google.com/vt/lyrs=s&x={x}&y={y}&z={z}"
        maxZoom={21}
        minZoom={4}
        minZoomIsDrawing={18}
        subdomains={["mt0", "mt1", "mt2", "mt3"]}
      />
      <ZoomControl />
    </Map>
  );
}

实例:https://codesandbox.io/s/keen-silence-vnt23

最佳答案

您需要使用效果来获取 map 实例以更改 map 边界。

检查 here了解更多信息。

const mapRef = useRef(null);

  useEffect(() => {
    const map = mapRef.current?.leafletElement;
    map.fitBounds([
      [59.569068610511465, 10.387057922780514],
      [59.565111563593824, 10.397184267640114]
    ]);
  }, []);

Demo

关于javascript - 动态边界更改不会在 'react-leaflet' 中产生任何影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64714683/

相关文章:

javascript - 如何阻止 jQuery 悬停泛滥?

javascript - 使用键插值和解构从状态对象中删除属性

r - 如何将 R map 中的 Leaflet 保存为 png 或 jpg 文件?

javascript - 传单折线箭头

javascript - 在 keyup 上向 API 发出请求,但我无法访问范围内的内容

javascript - 从文本框中获取.value

javascript异步调用和单线程模型

reactjs - 根据条件显示/隐藏链接 : React+Typescript

javascript - 在数组中递增单击 Redux 函数

javascript - Typescript 自动生成的 JS 文件 : "Uncaught TypeError: Failed to resolve module specifier"