react-map-gl样式未捕获错误:样式未加载

问题描述 投票:0回答:1

我正在使用React-MAP-GL,而我在尝试更新mapStyle对象时没有加载Style。

import React from 'react';
import ReactMapGL from 'react-map-gl';
import {defaultMapStyle, dataLayer} from './map-style.js';

import {fromJS} from 'immutable';
import geoJson from './cali.json';

export default class Map extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      mapStyle: defaultMapStyle,
      data: null,
      viewport: {
        width: 600,
        height: 800,
        latitude: 36.7783,
        longitude: -119.4179,
        zoom: 5,
      },
    };
  }

  componentDidMount() {
    window.addEventListener('resize', this._resize);
    this._loadData(geoJson);
  }


  _loadData = data => {
    const mapStyle = defaultMapStyle
      .setIn(['sources', 'incomeByState'], fromJS({type: 'geojson', data}))
      .set('layers', defaultMapStyle.get('layers').push(dataLayer));

    this.setState({data, mapStyle});
  };

  render() {
    return (
      <div>
        <ReactMapGL
          {...this.state.viewport}
          mapStyle={this.state.mapStyle}
          onViewportChange={viewport => {
            this.setState({viewport});
          }}
          mapboxApiAccessToken=""
        />
      </div>
    );
  }
}
reactjs react-map-gl
1个回答
2
投票

react-map-gl上的例子对我不起作用,这就是他们所做的。我认为他们的方法只是因为requestJson在回调中有this._loadData,但我正在加载geojson

componentDidMount() {
    window.addEventListener('resize', this._resize);
    this._resize();

    requestJson('data/us-income.geojson', (error, response) => {
      if (!error) {
        this._loadData(response);
      }
    });
  }

但我确实找到了一些方法来修复它:

选项1:

setTimeout(() => this._loadData(geoJson), 1);即使1毫秒,解决了原始方法的问题。

选项#2:不要使用ComponentDidMount加载数据,只需将onClick或'onScroll'事件放在其他地方加载数据。有点hacky ......

选项#3:使用onLoad!出于某种原因,我一开始并没有找到这种方法......

<MapGL
          ref={map => (this.mapRef = map)}
          {...this.state.viewport}
          mapStyle={this.state.mapStyle}
          onLoad={() => this._loadData(geoJson)}
          onViewportChange={viewport => {
            this.setState({viewport});
          }}
          mapboxApiAccessToken="8jiOnPbYA"
        />
© www.soinside.com 2019 - 2024. All rights reserved.