未捕获错误:未提供上下文:useLeafletContext() 只能在 <MapContainer>

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

我正在使用react-leaflet,并且我添加了一个带有事件处理程序的标记,单击即可缩放到该标记,但是当我尝试使用 const map=useMap() 时,我得到的只是这个错误 => :

Uncaught Error: No context provided: useLeafletContext() can only be used in a descendant of <MapContainer>

可能有类似的问题,但没有答案,有人可以帮忙解决吗? 这是我的代码:

const map = useMap()
 return (
        <div>
          <MapContainer
            className="leaflet-container"
            center={[33.8735578, 35.86379]}
            zoom={9}>

            <TileLayer
              attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
            />

            <Marker
              icon={port}
              eventHandlers={{
                click: (e) => {
                  map.setView(e.latlng, 14);
                },
              }}
              position={[33.90757548098519, 35.51700873340635]}
            ></Marker>
          </MapContainer>

谢谢!

javascript reactjs error-handling leaflet react-leaflet
4个回答
6
投票

我通过为标记创建一个单独的组件并在其中实现 useMap() 来解决它,它的工作原理如下:

import React from "react";
import { Marker, useMap } from "react-leaflet";

export default function Markerwhatever(props) {
  const map = useMap();

  return (
    <div>
      <Marker
        icon={props.icon}
        position={[33.91907336973602, 35.51552625946782]}
        eventHandlers={{
          click: (e) => {
            map.flyTo(e.latlng, 14);
          },
        }}
      ></Marker>
    </div>
  );
}


1
投票

如果您遇到问题

No context provided: useLeafletContext() can only be used in a descendant of <MapContainer>

升级react-leaflet和/或leaflet后,您应该删除并重新添加插件包(在我的例子中是标记集群插件),因为升级可能会在包版本中产生冲突。


0
投票

如果 useMap 不是从react-leaflet导入的,那么您使用的是旧版本。 v2 你需要运行

npm i @react-leaflet/core
如果问题仍然存在 删除node_modules并清除缓存
npm cache clear --force
并安装 npm i


0
投票

通过删除

react-leaflet-markercluster
并安装
@changey/react-leaflet-markercluster
解决了问题。

© www.soinside.com 2019 - 2024. All rights reserved.