尝试使用 react-leaflet-choropleth 映射等值线时出错:无法读取未定义的 属性 'map'

Error when trying to map a choropleth using react-leaflet-choropleth: Cannot read property 'map' of undefined

我正在尝试使用 react-leaflet-choroplethreact 中制作等值线。

我的传单工作正常。
现在,当我尝试使用库加载 geojson (crimes_by_district) 时,我在映射功能时遇到错误,特别是:

Cannot read property 'map' of undefined

看来我没有准确地引用正确的映射数组。

我查看了 git 存储库中的 issues 并尝试了这些建议,但没有成功。我想知道我是否引用了我正在使用的 geoJson 中的错误值。

下面是我的代码:

Leaf.js(在 App.js 中呈现)

import React, { Component } from 'react';
import { Map, TileLayer } from 'react-leaflet';
import classes from './leaf.module.css'
import Choropleth from 'react-leaflet-choropleth'
import geojson from "./assets/crimes_by_district.geojson";
    
const style = {
   fillColor: '#F28F3B',
   weight: 2,
   opacity: 1,
   color: 'white',
   dashArray: '3',
   fillOpacity: 0.5
};
    
class Leaf extends Component {
   render() { 
      return (         
         <Map>
           <Choropleth
             data= {{type: 'FeatureCollection', features: geojson.features}}
             valueProperty={(feature) => feature.properties.value}
             // visible={(feature) => feature.id !== active.id}
             scale={['#b3cde0', '#011f4b']}
             steps={7}
             mode='e'
             style={style}
             onEachFeature={
               (feature, layer) => layer.bindPopup(feature.properties.label)
             }
             ref={(el) => this.choropleth = el.leafletElement}
           />
         </Map>
      );
   }
}
    
export default Leaf;

使用与您包含的扩展类似的相同等值线库创建您自己的 choropleth wrapper,因为 react-leaflet-choropleth 似乎已过时:

function Choropleth() {
  const { map } = useLeaflet();

  useEffect(() => {
    fetch(
      "https://raw.githubusercontent.com/timwis/leaflet-choropleth/gh-pages/examples/basic/crimes_by_district.geojson"
    )
      .then((response) => response.json())
      .then((geojson) => {
        L.choropleth(geojson, {
          valueProperty: "incidents", // which property in the features to use
          scale: ["white", "red"], // chroma.js scale - include as many as you like
          steps: 5, // number of breaks or steps in range
          mode: "q", // q for quantile, e for equidistant, k for k-means
          style,
          onEachFeature: function (feature, layer) {
            layer.bindPopup(
              "District " +
                feature.properties.dist_num +
                "<br>" +
                feature.properties.incidents.toLocaleString() +
                " incidents"
            );
          }
        }).addTo(map);
      });
  }, []);

  return null;
}

然后将其作为 Map 子项导入:

<Map center={position} zoom={11} style={{ height: "100vh" }}>
        <TileLayer
          attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
          url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
        />
   <Choropleth />
</Map>

你可以通过传递你需要的各种变量作为道具来进一步扩展它。

Demo