在componentDidMount方法内部的事件监听器内设置状态

时间:2017-09-18 08:48:43

标签: reactjs

我有一个应用程序,我需要将用户的longitutde和纬度导出为props / state。我尝试在事件处理程序中多次设置状态,但我认为我的问题是我无法正确绑定'这个'到函数,因此我无法访问事件监听器内的状态。我尝试使用" bind(this)"几乎在componentsDidMount中的所有地方,但即使我使用它而没有得到错误,它似乎没有完成工作。我设置了多个console.log来查看最新情况。

换句话说,我想在事件句柄中使用setState - 似乎无法做到。以下是地图组件的代码:

import React from 'react';



class GoogleMap extends React.Component{

 constructor(){
super();
this.state = {
  lat: '',
  lon: ''
}
}

componentDidMount(){
  var map, infoWindow;


  map = new window.google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 15
  });


  // Try HTML5 geolocation.
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      };

      var marker = new window.google.maps.Marker({
        position: {
            lat: position.coords.latitude,
            lng: position.coords.longitude
        },
        map: map,
        draggable:true,
        title: 'Hello World!'})

    //   infoWindow.setPosition(pos);
    //   infoWindow.setContent('Location found.');
    //   infoWindow.open(map);
      map.setCenter(pos);

              //marker listeners
      window.google.maps.event.addListener(marker, 'dragstart', function() {
          console.log('marker dotkniety');
          document.getElementById('test').innerHTML = '<p>Currently dragging 
marker...</p>';
      });


      window.google.maps.event.addListener(marker, 'dragend', function(e) {
        console.log('marker upuszczony');
        document.getElementById('test').innerHTML = '<p>Want to export: 
Current Lat: ' + e.latLng.lat().toFixed(3) + ' Current Lng: ' + 
e.latLng.lng().toFixed(3) + '</p>';
        console.log(this, 'this inside the event listener');

      //   this.setState(() => {
      //    return {lat: e.latLng.lat(),
      //    lon: e.latLng.lng()}
      //  })

        }.bind(this)
      );


    }, function() {
      handleLocationError(true, map.getCenter());
    });



  } else {
    // Browser doesn't support Geolocation
    handleLocationError(false, map.getCenter());
  }


function handleLocationError(browserHasGeolocation, infoWindow, pos) {
  infoWindow.setPosition(pos);
  infoWindow.setContent(browserHasGeolocation ?
                        'Error: The Geolocation service failed.' :
                        'Error: Your browser doesn\'t support 
geolocation.');
  infoWindow.open(map);
}

console.log('DID MOUNT');
console.log(this);
console.log(this.state);
}


render(){

    return(

        <div>
            <div id='map' />
            <div id='test' />
        </div>
    )
}
}
export default GoogleMap 

1 个答案:

答案 0 :(得分:2)

你忘记了bind构造函数中的函数:

constructor() {
  super()

  this.handleLocationError = this.handleLocationError.bind(this)

  this.state = { ... }
}

componentDidMount() {
  var map, infoWindow;

  map = new window.google.maps.Map(document.getElementById('map'), {
    center: {lat: -34.397, lng: 150.644},
    zoom: 15
  })

  // Try HTML5 geolocation.
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
      var pos = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      }

      var marker = new window.google.maps.Marker({ ... })

      map.setCenter(pos);

      // marker listeners
      window.google.maps.event.addListener(marker, 'dragstart', () => {
        console.log('marker dotkniety');
        document.getElementById('test').innerHTML = '...';
      })

      window.google.maps.event.addListener(marker, 'dragend', (e) => {
        console.log('marker upuszczony')
        document.getElementById('test').innerHTML = '...'
        console.log('this inside the event listener')
      })
     }, () => this.handleLocationError(true, map.getCenter(), ??, map))
   } else {
     // Browser doesn't support Geolocation
     this.handleLocationError(false, map.getCenter(), ??, map)
  }

  console.log('DID MOUNT');
  console.log(this);
  console.log(this.state);
}

handleLocationError(browserHasGeolocation, infoWindow, pos, map) {
  infoWindow.setPosition(pos);
  infoWindow.setContent(browserHasGeolocation ?
                    'Error: The Geolocation service failed.' :
                    'Error: Your browser doesn\'t support geolocation.');
  infoWindow.open(map)

}

render() {
  ...
}