无法读取React中未定义函数的属性?

问题描述 投票:0回答:1

我正在使用 ReactJS 创建一个天气应用程序。以下是我的代码:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      temp: ""
    };
    this.getLocation = this.getLocation.bind(this);
    this.getWeather = this.getWeather.bind(this);
  }
  componentDidMount() {
    this.getLocation();
  }
  getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(success,error);
    }
    else {
      console.log("Not supported");
    }
    function success(position) {
      lat = position.coords.latitude;
      lon = position.coords.longitude;
      console.log(lat,lon);
      this.getWeather();
    }
    function error() {
      console.log("Unable to retrieve your location");
    }
  }
  getWeather() {
    fetch(`http://api.weatherapi.com/v1/current.json?key=${api}&q=${lat},${lon}&aqi=no`)
    .then((data) => data.json())
    .then((item) => {
      console.log(item);
    });
  }

api、lat 和 lon 是我在此之前声明并初始化的常量。这给出了错误:

Cannot read properties of undefined (reading 'getWeather')
    at success
javascript reactjs weather-api
1个回答
0
投票
function success(position) {
      lat = position.coords.latitude;
      lon = position.coords.longitude;
      console.log(lat,lon);
      this.getWeather();
    }

这里指的是“成功”范围

使用箭头功能

success=(position)=>{
      lat = position.coords.latitude;
      lon = position.coords.longitude;
      console.log(lat,lon);
      this.getWeather();
}
© www.soinside.com 2019 - 2024. All rights reserved.