[英]Setting state inside event listener which is inside componentDidMount method
I have an app where I need longitutde and latitude of user to be exported as props / state. 我有一个需要将用户的纬度和纬度导出为道具/状态的应用程序。 I tried setting state numerous times inside the event handlerer but I think my problem is that I cant properly bind 'this' to the function, therefore I cant access the state inside the event listener.
我尝试在事件处理程序中多次设置状态,但我认为我的问题是我无法正确地将“ this”绑定到函数,因此无法访问事件侦听器中的状态。 I tried using "bind(this)" virtually everywhere inside the componentDidMount but even when I used it without getting errors it doesnt seem to get the job done.
我尝试在componentDidMount内部几乎所有地方都使用“ bind(this)”,但是即使我使用它时也没有出现错误,但这似乎也无法完成工作。 I set up multiple console.logs to see whats going on.
我设置了多个console.logs以查看发生了什么。
In other words I want to setState inside the event handlerer - cant seem to do it. 换句话说,我想在事件处理程序中使用setState-似乎无法做到。 Here is the code for the map compononent:
这是地图组件的代码:
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
You forgot to bind
the function inside the constructor: 您忘记
bind
函数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() {
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.