简体   繁体   中英

WMSTileLayer is not updating after changing the layers parameter in react-leaflet

I am trying to update my WMS layer on react-leaflet v2.xx . The WMSTileLayer works only with the first layer and when I change the layers parameter on it, it shows the previously added layer. I have written following code,

<MapContainer
              whenCreated={(mapInstance) => {
                mapRef.current = mapInstance;
              }}
              center={[38.861, 71.2761]}
              zoom={5}
              zoomControl={false}
              style={{ width: "100%", height: "70vh" }}
            >
              <ZoomControl position="topright" />
              <TileLayer
                url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
                attribution="&copy; <a href='https://www.openstreetmap.org/copyright'>OpenStreetMap</a> contributors"
              />

              <WMSTileLayer
                  layers={this.props.wmsLayer}
                  url={`${process.env.REACT_APP_GEOSERVER_URL}/wms`}
                  transparent={true}
                  format={"image/png"}
              />

            </MapContainer>

So my question is, how to update the WMSTileLayer when my this.props.wmsLayer is updated?

You are using the MapContainer component, which makes me suspect you are actually using react-leaflet version 3. In react-leaflet version 3, many props are immutable , meaning once they are set, changing them from a react props perspective will do nothing. You would need to get a ref to the underlying L.TileLayer.WMS and call a method on it to change the layers. Unfortunately, the leaflet docs do not seem to show any methods to do that (ie like a setLayers function or something like that). You could call setUrl on the tilelayer, though I'm not sure that's what you want.

The easiest thing to do would be to add a key prop to your WMSTileLayer , and set it to some unique id that will force react to rerender when this.props.wmsLayer changes. I'm not sure what this.props.wmsLayer is, but if it has some unique url or id associated with it, set key={this.props.wmsLayer.id} or whatever you can, and react will force rerender that component. It's a bit overkill, but without some kind of setLayers function in the leaflet api, I'm not sure that there's a more proper way to do it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM