Всплывающее окно не будет оставаться открытым в реагирующей листовке после события onClick маркера - PullRequest
0 голосов
/ 02 апреля 2020

У меня есть листовка, которая создает маркеры из данных API. У маркеров есть onClick методы, которые извлекают данные из API открытой погоды без указания широты и долготы маркера. Данные о погоде должны отображаться во всплывающем окне, но всплывающее окно не будет оставаться открытым, после того, как onClick всплывающее окно только мигает и не остается открытым. Я вижу, что данные о погоде есть. Я думаю, что это может быть setState метод, который закрывает всплывающее окно. Как я могу держать всплывающее окно открытым? Спасибо.

Вот компонент карты

import React, { Component } from 'react';
import L, { tooltip } from 'leaflet';
import { Map, Marker, Popup, TileLayer } from 'react-leaflet';
import { Button } from 'react-bootstrap';

const position = [62.241581, 25.758742];
let weather = [];



class Kartta extends Component {
  constructor(props) {
    super(props);
    this.state = {
        places: [],
        sijaintisi: [],
        map: null,
        userLocation: [62.241581, 25.758742],
        weather: [],
        position: [62.241581, 25.758742],
        zoom: 7
    };

}
  componentDidMount() {
    this.getUserLocation();
  }

  componentDidUpdate() {
    console.log('update0');
    if (this.props.updateMap) {
      console.log('update1');
      if (this.props.updateMap !== this.state.places) {
        console.log('update2');
        this.setState({
          places: this.props.updateMap
        })
      }
    }
  }

  fetchPosition = (tänne) => {
    this.setState({ sijaintisi: tänne})
  }

  fetchWeather = (lat, lon) => {
    fetch('http://myurl/api/v1/wheather?lat=' + lat + '&lon=' + lon)
    .then(res => res.json())
    .then((data) => {
        this.setState({ weather: data })
    })
    .catch(console.log(this.state.weather))
  }

  iconSize = (iconName) => {
    var icon = iconName.toLowerCase().split('/')[0]
    if (icon === 'kuntokeskus' || icon === 'kuntosali' || icon === 'tekojääkenttä') {
      return 20, 30
    }
    else if (icon === 'ulkoilumaja' || icon === 'kampailulajien sali' || icon === 'koripallokenttä') {
      return 30, 30
    }
    else if (icon === 'beachvolleykenttä') {
      return 15, 30
    }
    else {
      return 15, 30
    }
  }

  getUserLocation = () => {

    if(navigator.geolocation)
    {

    navigator.geolocation.getCurrentPosition(position => {


        this.setState({
            userLocation: [position.coords.latitude, position.coords.longitude, position.coords.accuracy]
        })


     this.fetchPosition(this.state.userLocation);


    }, error => console.log(error.message), { 
        enableHighAccuracy: true
    });
  }

}

totop = (e) => {

  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
}


  MapComponent = () => {
    if(this.state.places.length > 0){
      return (            
        <Map center={this.state.position} zoom={this.state.zoom} maxZoom={18} minZoom={6}>
        <Button onClick={this.totop} style={{zIndex:999, position:"absolute", left:50,top:17}} >Valikko</Button>
            <TileLayer
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
              attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
            />
            {this.state.places.map((kohde) => (
                <Marker key={'key' + kohde.lat + kohde.lon + Math.random()} onClick={() => this.fetchWeather(kohde.lat, kohde.lon)} position={[kohde.lat, kohde.lon]} icon={
                    new L.Icon({
                        iconUrl: require('../img/green-icon.png'),
                        iconSize: new L.Point(this.iconSize(kohde.typeName)),
                    })
                }>
                    <Popup autoClose={false} maxWidth={1000}>
                        <div>
                          <h1>{kohde.name}</h1>
                          <p>{kohde.typeName}</p>
                          <p>Osoite: {kohde.address}</p>
                          <p>Paikkakunta: {kohde.city}, {kohde.cityPart}</p>
                          <p>Puhnro: {kohde.phone}</p>
                          <p>S-posti: {kohde.email}</p>
                          <p className="text-justify">WWW: <a href={kohde.www}>{kohde.www}</a></p>

                          <h3>Sää</h3>
                          <p>{this.state.weather.desc}</p>
                          <p>{this.state.weather.icon}</p>
                          <p>{this.state.weather.temp}</p>
                          <p>{this.state.weather.wind}</p>
                        </div>
                    </Popup>
                </Marker>
              ))}
              {this.state.sijaintisi.map((kohde2) => (
                <Marker key={Math.random()} position={this.state.sijaintisi} icon={
                    new L.Icon({
                      iconUrl: require('../img/red-icon.png'),
                      iconSize: new L.Point(this.iconSize("red-icon.png"))

                    })
                }>

                    <Popup><h1>Sijaintisi</h1></Popup>

                </Marker>

              ))}
          </Map>
      )
    }
    else {
      return (

        <Map center={position} zoom={7} maxZoom={18} minZoom={6}>
          <Button onClick={this.totop} style={{zIndex:999, position:"absolute", left:50,top:17}} >Valikko</Button>
            <TileLayer
              url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
              attribution="&copy; <a href=&quot;http://osm.org/copyright&quot;>OpenStreetMap</a> contributors"
            />

              {this.state.sijaintisi.map((kohde2) => (
                <Marker key={Math.random()} position={this.state.sijaintisi} icon={
                    new L.Icon({
                      iconUrl: require('../img/red-icon.png'),
                      iconSize: new L.Point(this.iconSize("red-icon.png"))

                    })
                }>

                    <Popup><h1>Sijaintisi</h1></Popup>

                </Marker>

              ))}
          </Map>
      )
    }
  }

  render() {
      return (
          <div id="mapid" className="h-100 w-100">

            <this.MapComponent />
          </div>

      )
  }
}

export default Kartta;
...