React 和 Leaflet - 显示图层的问题

React and Leaflet - issue displaying a layer

我正在尝试在 React 项目中使用 Leaflet。 我的目标实际上非常基本:只显示一个 openstreetMap 图层(没有标记或东西)

这是我的代码:

import React, { Component } from 'react';
import L from 'leaflet';

class MyMap extends Component {

  constructor(){
    super();
    this.state ={
      map:null,
    };
  }

componentDidMount() {
        var map = L.map('map', {
            minZoom: 2,
            maxZoom: 20,
            layers: [L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'})],
            attributionControl: false,
        });
        return this.setState({
            map: map
        });
    }
    render() {
        return (
            <div id='map'> </div>
        );
    }

}

ReactDOM.render(
  <MyMap />,
  document.getElementById('root')
);

每次显示地图时遇到保存问题: 它看起来像这样:(并非所有显示的图块都是叠加问题): Screenshot

有人遇到这个问题或有任何解决方案吗?

感谢您的帮助

首先,确保您已经加载了 Leaflet 的样式表:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css">

瓦片随机播放是因为样式表尚未加载或在 React 实际渲染地图目标后执行了 Leaflet。我们可以做的是为初始化添加一个超时:

class MyMap extends React.Component {
  constructor() {
    super();
    this.state ={
      map: null,
    };
  }

  componentDidMount() {
    setTimeout(() => {
      var map = L.map('map', {
          minZoom: 2,
          maxZoom: 20,
          layers: [L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {attribution: '&copy; <a href="http://openstreetmap.org">OpenStreetMap</a> contributors, <a href="http://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>'})],
          attributionControl: false,
      });
      map.fitWorld();
      return this.setState({
          map: map
      });
    }, 100)
  }

  render() {
    return <div id="map" style={{ height: 300 }}></div>;
  }
}

ReactDOM.render(
  <MyMap />,
  document.getElementById('View')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.1/leaflet.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/leaflet/0.7.7/leaflet.css">
<div id="View"></div>