首页 > 解决方案 > 单击按钮显示 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。我不确定如何解决这个问题。任何帮助将不胜感激,谢谢。

标签: reactjsgeojsonreact-leaflet

解决方案


如果您查看GeoJSON 的 react-leaflet 文档,您会看到该data属性不是 mutable,这意味着GeoJSON组件在创建后不会响应dataprop 中的更改。这是 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>
    )
}

推荐阅读