使用@urbica/react-map-gl 动态更新 Mapbox 图层

Dynamic Mapbox layer update using @urbica/react-map-gl

我无法在 <Layer source-layer={this.state.layer} /> 中动态更改 source-layer。通过按下按钮,我将状态更改为 layer: 'building'layer: 'road'<Layer source-layer={this.state.layer} />

内部不会发生更改

示例代码:https://codesandbox.io/s/compassionate-brook-l1psj

class App extends React.Component {
  state = {
    mapStyle: "mapbox://styles/mapbox/light-v9",
    viewport: {
      latitude: 44.8016,
      longitude: -68.7712,
      zoom: 15
    },
    layer: "building"
  };

  render() {
    const { mapStyle } = this.state;
    return (
      <div className="App">
        <div>
          <button
            onClick={() => {
              if (this.state.layer === "road") {
                this.setState(state => {
                  return {
                    ...state,
                    layer: "building"
                  };
                });
              } else {
                this.setState(state => {
                  return {
                    ...state,
                    layer: "road"
                  };
                });
              }
            }}
          >
            Change Style
          </button>
        </div>
        <MapGL
          style={{ width: "100%", height: "400px" }}
          mapStyle={mapStyle}
          accessToken={MAPBOX_ACCESS_TOKEN}
          onViewportChange={viewport =>
            this.setState(state => {
              return {
                ...state,
                viewport
              };
            })
          }
          {...this.state.viewport}
        >
          <Source
            id="maine"
            type="vector"
            url="mapbox://mapbox.mapbox-streets-v8"
          />
          {console.log(this.state.layer)} // Here I see that the state is changing
          <Layer
            id="maine"
            type="fill"
            source="maine"
            source-layer={this.state.layer}
            paint={{
              "fill-color": "#088",
              "fill-opacity": 0.8
            }}
          />
        </MapGL>
      </div>
    );
  }
}

此问题已解决。谢谢。 https://github.com/urbica/react-map-gl/issues/273