У меня есть следующая ошибка в строке 20, где состояние установлено для showNoResultsMessage
TypeError: this is undefined
Я думаю, что это может быть связано с проблемой в контексте, который называется this.Тем не менее, я не уверен, как обойти проблему или что this
в этом случае, когда он устанавливает состояние.Я предполагаю, что это пусто и должно быть как-то пропущено.
Любая помощь будет оценена.Заранее спасибо.
import React from 'react';
import ReactDOM from 'react-dom';
class MainApp extends React.Component {
constructor(props) {
super(props);
this.getLocation();
}
getPlaces(position) {
const mainDiv = document.querySelector("#main-app");
const mapTag = mainDiv.getAttribute('data-map');
let apiUrl = "https://example.com/places.json";
const url = apiUrl + "?lat=" + position.coords.longitude + "&lon=" + position.coords.latitude + "&tags=" + mapTag;
console.log("mapag: " + mapTag);
console.log("url: " + url);
this.setState({showNoResultsMessage: true});
};
/**
* Could not get location, present error message
*/
locationErrorHandler(err) {
if (err.code == 1) {
alert("Error: Access is denied!");
} else if (err.code == 2) {
alert("Error: Position is unavailable!");
}
}
/**
* First attempts to get location and from there, runs the api call to get places.
*/
getLocation() {
if (navigator.geolocation) {
// timeout at 60000 milliseconds (60 seconds)
var options = {timeout: 60000};
navigator.geolocation.getCurrentPosition(this.getPlaces, this.locationErrorHandler, options);
} else {
alert("Sorry, browser does not support geolocation!");
}
}
render() {
return (
<div>
<div>Get Started</div>
</div>
);
}
}
ReactDOM.render(
<MainApp/>,
document.getElementById('main-app')
)