React, 错误显示 Leaflet (Map) Foreach Modal

React, Error Display Leaflet (Map) Foreach Modal

我的问题实际上是在模式内显示地图,但是当我循环显示每个数据时出现错误:

Error: Map container not found.

那太糟糕了,因为那花了我一整天的时间,但没有任何结果。

Class 包含(地图):

import React, { Component } from 'react'
import {
  Modal, Form, Input, Label, message, Tooltip, Icon, Cascader, Select, Row, Col, Checkbox, Button, AutoComplete,
} from 'antd';
import 'antd/dist/antd.css';
import L from 'leaflet'
import 'leaflet/dist/leaflet.css'


export default class MoreInfo extends Component {

  state = {
    visible: false
  }

  showModal = () => {
    this.setState({
      visible: true,
    });
  }

  handleOk = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  }

  handleCancel = (e) => {
    console.log(e);
    this.setState({
      visible: false,
    });
  }

  /****************************** */


 
  handlePositionMap = () => {
    const center = ["34.0389", "-6.8166"];

    let map2 = document.querySelector('#map');

    map2 = L.map('map').setView(center, 13);

    let token = 'pk.eyJ1IjoidnVkaWRlIiwiYSI6ImNqdWw0bmVlNDF3eGs0MW9hYjlyNWI1d3gifQ.BF_c4537GAPelCGeJwMqCg'
    let icon = L.icon({
        iconUrl: 'https://unpkg.com/leaflet@1.4.0/dist/images/marker-icon.png',
    });
    L.tileLayer(`https://api.mapbox.com/v4/mapbox.streets/{z}/{x}/{y}.png?access_token=${token}`, {
        maxZoom: 18,
        minZoom: 7,
        attribution: '© <a href="#">Golan</a>'
    }).addTo(map2);
    L.marker(center, {icon: icon}).addTo(map2);

  }

  componentDidMount(){
    this.handlePositionMap();
  }



  render() {
    return (
      <div>

        <Button type="primary" onClick={this.showModal}>
          More
        </Button>
        <Modal
          title="More Info"
          visible={this.state.visible}
          onOk={this.handleOk}
          onCancel={this.handleCancel}
        >



        <Form.Item label="Location" >
          <div id="map" style={{"width": "206px","height": "113.8px"}} ></div>
        </Form.Item>


          <p>Some contents...</p>
          <p>Some contents...</p>
          <p>Some contents...</p>
        </Modal>
      </div>


    )
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>

二、调用地点:

class Place extends Component {

  constructor(props){
    super(props);


    this.state = {
      place: this.props.place,
      locals: this.props.locals,
      firstLoad: 0,
      cartItems: [],
      buttonName: "",
    }
  }


  componentDidMount(){
    console.log("[Place] -> componentDidMount() : ");
    console.log(this.state.place);

    if(localStorage.getItem("cartItems")){
      this.setState({ cartItems: JSON.parse(localStorage.getItem("cartItems")) });
    }
    //this.handlePositionMap();
    console.log("-----------------------------------");
  }

 

  render(h) {

    console.log("Place :", this.props.place);

    return (

    <div>


      { this.props.place ? (

            <Card key={this.props.place.id }  >
                <CardMedia
                    style={{height: 0, paddingTop: '55.25%'}}
                    image="https://s3-eu-west-1.amazonaws.com/parkings.bepark.eu/488/5ab8e253a27cb4.58776216.jpeg"
                    title="test"

                />


        
                <CardContent>
                    <Typography gutterBottom variant="headline" component="h2">
                        { this.capitalize(this.props.place.local_name) }
                    </Typography>
                    <Typography component="p">
                        { this.capitalize(this.props.place.local_address) }
                    </Typography>
                </CardContent>



                <CardFooter>

                <CardActions>


                    <MoreInfo
                      place={this.props.place}
                      locals={this.props.locals}
                    />

                    &nbsp;

                    <Modal
                        modal_name="Edit"
                        place={this.props.place}
                        locals={this.props.locals}
                        handleEdited={this.props.handleEdited}
                        handleLoadPlace={this.props.handleLoadPlace}
                    />

                    <Popconfirm title="Are you sure?" onConfirm={() => this.handlClickDelete(this.props.place.id)} okText="Yes" cancelText="No">
                      <Button size="small" variant="contained" color="secondary" >
                          Delete
                      </Button>
                    </Popconfirm>

                </CardActions>

                   

                </CardFooter>


            </Card>



        ): null


        }
      </div>
    );
  }

}

export default Place;

生成所有位置的Class :

/ ...

            { (Array.isArray(this.state.places) && this.state.places.length) ? (this.state.places.map( place =>  (
                <Grid item xs={12} sm={3} lg={4} xl={3} key={place.id} >
                    <Place
                        place={place}
                        locals={this.state.locals}
                        handleDelete={this.handleDelete}
                        handleLoadPlace={this.handleLoadPlace}
                        handleEdited={this.handleEdited}
                        handleAddToCart={ this.test.bind(this) }
                        handleCartPlaceExists={this.handleExistPlace.bind(this)}
                    />
                </Grid>
            ))): "No Places found" }


/...

结果:

Could you Help Me please to find the solution, and I'm looking forward to your answers Thank You ^_^

如错误所述您的示例中缺少地图容器,来自documentation

Instantiates a map object given the DOM ID of a <div> element

这是一个简单的例子:

class Map extends Component {

  componentDidMount(){
    const map = L.map('map').setView([51.505, -0.09], 13);

    L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B5aw', {
        maxZoom: 18,
        attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, ' +
            '<a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, ' +
            'Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
        id: 'mapbox.streets'
    }).addTo(map);
  }


  render() {
    return (
        <div id="map"/>
    );
  }
}

Demo