首页 > 解决方案 > 反应 this.SetState 未定义 - 嵌套函数

问题描述

制作我的第一个反应应用程序。我想根据用户的位置更新谷歌地图 api。我收到错误“这是未定义的”。我理解使用 .bind(this) 并包装在箭头函数中,但认为这种情况有点不同,因为我在嵌套函数中设置状态:

constructor(props) {
    super(props);
    
    this.state = {zip: null, lat: 40.5304 , lng: -100.6534 , zoom: 3.8 };

    this.updateCurrentPosition= this.updateCurrentPosition.bind(this);
  }
  
  //...
  
updateCurrentPosition = () => {
    navigator.geolocation.getCurrentPosition(success, error);
    
      function success(pos) {
        this.setState(`{lat: ${pos.coords.latitude}, lng: ${pos.coords.longitude}, zoom: ${3.8}`)  
      }
    
      function error(err) {
        console.warn(`ERROR(${err.code}): ${err.message}`);
      }; 
  }

  ops = () => { 
    return {
      center: { lat: this.state.lat, lng: this.state.lng },
      zoom: this.state.zoom
    }
  };

标签: javascriptreactjs

解决方案


箭头函数自动将函数绑定到父类。如果一个函数没有绑定,或者不是箭头函数,“this”将只引用函数本身,即使它是嵌套的。您的成功函数(以及失败函数)未绑定到父类,因为您既没有绑定它也没有将其定义为箭头函数。


推荐阅读