【问题标题】:Why Mapbox gl changes its style without changing state with setStyle call only in React?为什么 Mapbox gl 仅在 React 中通过 setStyle 调用更改其样式而不更改状态?
【发布时间】:2018-07-06 08:44:58
【问题描述】:

我认为 react 组件依赖于状态来改变/渲染视图,但是为什么调用 mapbox-gl 的 setStyle 函数会改变地图的样式而不改变状态?

class WebMap extends React.Component {
state = {

    style:"mapbox://styles/noeltech/cj6jcxggi5jpr2smhnsb42h3i",
    lng:122.5683,
    lat:10.7028,
    zoom:14
};
componentDidMount(){
    const {lng, lat,zoom,style } = this.state;
    const map = new mapboxgl.Map({
        container: this.mapContainer,
        style: style,
        center: [lng, lat],
        zoom
    });

    map.on('move', () => {
        const {lng, lat } =map.getCenter();

        this.setState({
            lng: lng.toFixed(4),
            lat: lat.toFixed(4),
            zoom: map.getZoom().toFixed(2)
        });
        console.log(`lng: ${lng}  lat:${lat}`)
    });

    setTimeout(()=>{
        // this.setState({style:"mapbox://styles/noeltech/cj6zr2fda9jyz2smst427o4gb"})
        map.setStyle("mapbox://styles/noeltech/cj6zr2fda9jyz2smst427o4gb")
        console.log(this.state.style)
    },5000);

【问题讨论】:

    标签: reactjs react-redux mapbox-gl-js


    【解决方案1】:

    map 变量是 Mapbox 地图实例的引用,因此当您制作 map.setStyle() 时,您正在更改此引用实例的样式,this.state 是您当前组件的状态重新包装map-container。内部变化不会触发外部状态变化,只有当地图实例有,例如,像 onStyleChange() 这样的一些监听器

    【讨论】:

    • 感谢您的参考见解..现在我明白了
    【解决方案2】:

    我的 setState 函数中缺少我必须添加的代码:

       function() {
                    map.setStyle(this.state.style)
    

    这样

       setTimeout(()=>{
            this.setState({
                style: "mapbox://styles/noeltech/cj6zr2fda9jyz2smst427o4gb"
            },
                function() {
                    map.setStyle(this.state.style)
                }
            )        
        },5000);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-01
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 2016-01-02
      • 1970-01-01
      • 2017-12-28
      • 2016-07-10
      相关资源
      最近更新 更多