我在用反应传单库。特别是,我使用库附带的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中的StateMap组件,但它没有。我还尝试在StateMap中创建状态变量,当支柱" geojson“被更改时,状态变量会发生变化,但这也不会改变正在使用的geojson。我不知道如何解决这个问题。任何帮助都将不胜感激,谢谢。
发布于 2021-03-12 04:36:14
如果您查看react GeoJSON的传单文档,您将看到data
属性是不可变的,这意味着GeoJSON
组件在创建后不会响应data
支柱中的更改。这是一个新的特性与反应-传单v3,这是到处都在图书馆的地方,并有助于避免不必要的改变反应组件。
因此,要更改数据,您需要获得一个参考文件到基础传单元素,并从那里执行它,就像在普通传单应用程序中那样。
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>
)
}
https://stackoverflow.com/questions/66593794
复制相似问题