javascript - 设置状态导致 TypeError: this is undefined
问题描述
我在状态设置为的第 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')
)
解决方案
您应该像这样绑定构造函数中的函数:
this.getLocation.bind(this);
或使用如下箭头函数语法:
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!");
}
}
推荐阅读
- python - 滑动窗口问题的时间复杂度
- python - 如何使用 Python 图像库中的“图像”函数中的像素数据写入二进制文件?
- python - 使用 python 在 Barchart 网站上抓取表格
- machine-learning - XGBoost 特征具有更高的特征重要性,但准确性更低
- git - 如何仅在我的工作忽略合并的情况下运行 difftool
- r - 限制数据框中所有单元格的字符串长度?
- python - 如何基于行创建 seaborn clustermap 并提取行标签?
- python - IndexError:创建均匀粒子时数组的索引过多
- dataframe - 如何在matplotlib中增加条形之间的空间并增加条形宽度
- environment-variables - 如何从 XCUITest 代码访问 xcconfig 变量