如何解决React:如何使用传单通过获取调用来映射geojson?
我正在尝试绘制我在 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
(这称为道具钻孔)和那么您将使用 geojson 作为 url 来重新获取数据。如果您已经在 App 上获取了数据,为什么要在 Choro
上重新获取它们?最重要的是,您将 geojson
数据用作 url。再看看你的代码。
最后但并非最不重要的是,当您使用 then
then
时,您不能同时使用 async
await
,因为这两个用途完全相同。它们用于以同步方式进行异步调用。
应该是这样demo
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。