Reactjs Can';t在未安装的组件上调用setState

Reactjs Can';t在未安装的组件上调用setState,reactjs,google-maps,Reactjs,Google Maps,这不是更新状态,而是说“而是直接将This.state分配给它,或者在包装器组件中用所需的状态定义一个state={};类属性。” 导出类Smap扩展组件{ 建造师(道具){ 超级(道具); 此.state={ 我的时间:1,我的时间:1 }; this.getCoords=this.getCoords.bind(this); } componentDidMount(){ 这个.getCoords(); } getCoords=()=>{ 设a=1; 设b=1; navigator.geoloc

这不是更新状态,而是说“而是直接将
This.state
分配给它,或者在包装器组件中用所需的状态定义一个
state={};
类属性。”

导出类Smap扩展组件{
建造师(道具){
超级(道具);
此.state={
我的时间:1,我的时间:1
};
this.getCoords=this.getCoords.bind(this);
}
componentDidMount(){
这个.getCoords();
}
getCoords=()=>{
设a=1;
设b=1;
navigator.geolocation.getCurrentPosition(函数(位置){
a=位置坐标纬度;
b=位置坐标经度;
console.log(“纬度为:”,位置.坐标.纬度);
log(“经度为:”,位置.坐标.经度);
});
这是我的国家({
我的拉丁语:a,
我的儿子:b
})
}   
render(){
常量集装箱样式={
位置:'相对',
宽度:“100%”,
身高:“100%”
}
返回(
{这个州,我的祖国}{这个州,我的祖国}
{console.log(lat1,lat2)}
);
}
}
导出默认GoogleApprapper({
apiKey:(“Aizasybxnlwekk2l9yalt5f0do4hvcmtywepge”)
})(Smap)

它看起来像是您拥有的
this.stateState
直接从变量
a
b
的初始值获取值。您应该将其放在
navigator.geolocation.getCurrentPosition()
中。但是,如果直接将其放入代码中,它将返回一个错误,说明未定义
setState
。我假设这是因为您在
navigator.geolocation.getCurrentPosition()中使用
函数(位置)
。要解决此问题,您可以更改此部件:

getCoords = () =>{
    let a=1;
    let b=1;
    navigator.geolocation.getCurrentPosition(function(position) {
      a=position.coords.latitude;
      b=position.coords.longitude;
      console.log("Latitude is :", position.coords.latitude);
      console.log("Longitude is :", position.coords.longitude);
    });
    this.setState({
      my_lat:a,
      my_lon:b
    })
  }   
为此,我使用
position=>
而不是
函数(position)

这是一本书

请从您的问题中删除API密钥,以后不要在公共站点发布您的API密钥。您还可以在问题中添加
google-maps
标记,以增加关注google-maps标记的人的可见性

getCoords = () =>{
    let a=1;
    let b=1;
    navigator.geolocation.getCurrentPosition(function(position) {
      a=position.coords.latitude;
      b=position.coords.longitude;
      console.log("Latitude is :", position.coords.latitude);
      console.log("Longitude is :", position.coords.longitude);
    });
    this.setState({
      my_lat:a,
      my_lon:b
    })
  }   
getCoords = () => {
    let a = 1;
    let b = 1;

    navigator.geolocation.getCurrentPosition(position => {
      a = position.coords.latitude;
      b = position.coords.longitude;
      console.log("Latitude is :", position.coords.latitude);
      console.log("Longitude is :", position.coords.longitude);
      this.setState({
        my_lat: a,
        my_lon: b
      });
    });
  }