我无法source-layer
动态更改<Layer source-layer={this.state.layer} />
. 通过按下按钮,我将状态更改为layer: 'building'
orlayer: '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>
);
}
}