reactjs - 没有自定义库的 React 中的 Google 地图:无法读取 null 的属性 setState
问题描述
我目前在没有库的情况下在 React 中使用谷歌地图。我不断收到该错误(无法读取 null 的属性 setState),我知道这与在函数中使用“this”有关。在这种特殊情况下,我不知道如何解决它。
方法
getGPS = () =>{
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
let start = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
this.setState({start: start})
});
} else {
let start= {lat:"-34.603474", lng:"-58.381592"};
this.setState({start: start})
};
this.calculateAndDisplayRoute()
}
地图组件
<Map
id="myNewMap"
float="right"
width= "50%"
options={{
center: {lat: this.state.currentMarker[0].getPosition().lat(), lng: this.state.currentMarker[0].getPosition().lng()},
zoom: 18,
disableDefaultUI: true,
}}
onMapLoad={map => {
this.newMap = map;
{this.getGPS()}
}
}
/>
解决方案
function(position) {
let start = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
this.setState({start: start})
}
你是对的,这是this
. JavaScript 认为您this
在函数内引用。如果您将函数更新为箭头函数,this
则会使用封闭词法范围的值,这将是您的组件。
navigator.geolocation.getCurrentPosition(position => {
let start = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
this.setState({start: start})
};
推荐阅读
- c# - 如何使用 C# 从 Visual Studio 传递管道变量
- python - 广播变量和 mapPartitions
- openshift - 公开注册表的 OpenShift 权限问题
- reactjs - 如何通过创建反应应用程序解决节点模块the-noun-project(api包装器)的cors问题
- css - 使用 css 的顶部定位水平滚动,使用变换时滚动条不可见
- sql - 无法在 CONCAT 语句中使用计算值
- python - 使用 macOS 在 python 中加载 dylib 库时出现问题
- pandas - 如何对熊猫中的独特项目进行累计总和?
- azure-devops - 无法从存储库中删除 azure 组
- sql-server - 取消嵌套 SQL Server 2014 中的字段