React:如何使用传单通过获取调用将geojson映射到状态?

React: How to map a geojson via fetch call to state using leaflet?

我正在尝试绘制我在 react 中获取并使用 react-leaflet 的 geojson。当我在本地导入时,我能够映射 geojson。现在我通过 https 获取原始数据,然后设置状态以尝试将该状态作为道具传递。但是 this.state.geojson.

没有映射

我想我可能设置了错误的状态或误解了渲染的工作方式。一些指导将不胜感激。下面是一些代码:

App.js

...
  fetchData = async () => {
      let data = await
        fetch(
          "https://raw.githubusercontent.com/timwis/leaflet-choropleth/gh-pages/examples/basic/crimes_by_district.geojson"
          )
          .then((response) => response.json())
          .then((geojson) => {
            return geojson
          })

      console.log("my_data: ", data)
      this.setState({ geojson: data, loaded: 2 })
      return data
}
...

 {/** MAP */}
            <div>
              {this.state.geojson && <Leaf
                viewPort={this.state.viewPort}
                geojson={this.state.geojson} 
              />}
            </div>
...

Leaf.js

...
<Map>
...
<Choro
  geojson={this.props.geojson}
/>
</Map>

Choro.js

import { useEffect } from 'react';
import { useLeaflet } from "react-leaflet";
var L = require('leaflet')
require('leaflet-choropleth')


function Choro(props) {
    const { map } = useLeaflet();
  
    useEffect(() => {
      fetch(
        //"https://raw.githubusercontent.com/timwis/leaflet-choropleth/gh-pages/examples/basic/crimes_by_district.geojson"
        `${props.geojson}`  
      )
        .then((response) => response.json())
        .then((geojson) => {
          L.choropleth(geojson, {
            valueProperty: "DIFF", // 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(
                "Total " +
                  feature.properties.DIFF +
                  "<br>" //+
                  // feature.properties.incidents.toLocaleString() +
                  // " incidents"
              );
            }
          }).addTo(map);
        });
    }, []);
  
    return null;
 }

 export default Choro;

状态变化应该发生在 then 内部而不是外部:

fetchData =  () => {
      fetch(
          "https://raw.githubusercontent.com/timwis/leaflet-choropleth/gh-pages/examples/basic/crimes_by_district.geojson"
          )
          .then((response) => response.json())
          .then((geojson) => {
             console.log("my_data: ", geojson);
             this.setState({ geojson, loaded: 2 })

          })

}

但是,我仍然不确定你在做什么,因为你在 App 上获取 geojson,然后将数据传递给 Leaf,然后传递给 Choro(这称为 prop drilling ) 然后你使用 geojson 作为 url 来重新获取数据。如果您已经在 App 上获取了数据,为什么要在 Choro 上重新获取它们?最重要的是,您将 geojson 数据用作 url。再看一下您的代码。

最后但并非最不重要的一点是,当您使用 then then 时,您不能同时使用 async await,因为这两者的用途完全相同。它们用于以同步方式进行异步调用。

这是应该的demo