reactjs - 单击按钮显示 GeoJSON 类的新 geojson 数据
问题描述
我正在使用 React 传单库。特别是,我使用库附带的 GeoJSON 类来呈现由 geojson 描述的地图。目前我的课是这样的:
const MyMap = () => {
const [stateGeoJSON, setStateGeoJSON] = useState(exampleGeoJSON)
const setStateGeoJSON = (newJson) => {
setStateGeoJSON(newJson)
}
return (
<div>
<MapContainer
style={{ height: '90vh'}}
zoom={zoom}
maxZoom={12}
minZoom={5}
center={mapCenter}
zoomControl={false}
maxBounds={mapCenter}
maxBoundsViscosity={1.0}
>
<StateMap geojson={stateGeoJSON}/>
</MapContainer>
</div>
)
}
我还有一个名为 StateMap 的类,它位于 MyMap 类中,如下所示:
const StateMap = ({ geojson }) => {
return (
<div>
<GeoJSON
style={districtStyleDefault}
data={geojson.features}
onEachFeature={onEachState}
/>
</div>
)
}
我没有把函数“onEachFeature”或样式放在这篇文章中,但它们就在那里。基本上,我的 StateMap 类从 MyMap 中获取一个名为“geojson”的道具,该道具将用于在 StateMap 中呈现地图。这一切都有效。
问题是我试图通过单击按钮来更改 StateMap 内部使用的 geojson。用户单击按钮后,将使用新的 geojson 调用 setStateGeoJSON。然后更改名为“stateGeoJSON”的状态变量。我认为这会更新 StateMap 中的 GeoJSON 组件,但事实并非如此。我还尝试在 StateMap 中创建状态变量,当道具“geojson”更改时会更改,但这也不会更改正在使用的 geojson。我不确定如何解决这个问题。任何帮助将不胜感激,谢谢。
解决方案
如果您查看GeoJSON 的 react-leaflet 文档,您会看到该data
属性不是 mutable,这意味着GeoJSON
组件在创建后不会响应data
prop 中的更改。这是 react-leaflet v3 的一个新功能,它在库中随处可见,有助于不导致不必要的 react 组件重新渲染。
因此,要更改数据,您需要获取底层传单元素的引用,并从那里进行操作,就像在普通传单应用程序中一样。
const StateMap = ({ geojson }) => {
// get a ref to the underlying L.geoJSON
const geoJsonRef = useRef()
// set the data to new data whenever it changes
useEffect(() => {
if (geoJsonRef.current){
geoJsonRef.current. clearLayers() // remove old data
geoJsonRef.current.addData(geojson) // might need to be geojson.features
}
}, [geoJsonRef, geojson])
return (
<div>
<GeoJSON
ref={geoJsonRef}
style={districtStyleDefault}
data={geojson.features}
onEachFeature={onEachState}
/>
</div>
)
}
推荐阅读
- javascript - 在名为 Mumbling 的 Codewars 任务的解决方案中找到正确的正则表达式的问题
- c# - 反斜杠的可变长度后视
- html - 未捕获的 TypeError:非法调用。尝试在 Nodejs 中使用 ajax 发帖时
- c++ - 来自 std::filesystem::u8path(const char8_t*) 的 VS 错误
- java - Spring boot @JoinClumn ManyToOne 关系列不存在
- c++ - 如果我用数组的-1索引交换一个元素怎么办
- javascript - 在Vuejs中验证电子邮件之前如何禁用按钮?
- mysql - 如何从 JOIN 中选择一些东西?SQL
- android - Insta 卷轴之类的功能(使用 Exoplayer)具有分页和下拉刷新功能
- python - 在 Django 中构建一个可以处理并发请求的代理