首页 > 解决方案 > 没有自定义库的 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()}
} 
}
/>

标签: reactjs

解决方案


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})
    };

推荐阅读