反应NativeTypError:未定义不是对象

时间:2018-12-03 11:14:08

标签: api react-native promise

我在进行API调用时遇到此错误: Possible Unhandled Promise Rejection (id:0): TypError: undefined is not an object(evaluating 'json.main.temp')

这是我的状态:

this.state = {
      weather:{
        city: null,
        temperature: null,
        wind:{
          direction: null,
          speed: null
        }
      },
      latitude: null,
      longitude:null,
      error: null
    }

我的componentWillMount函数:

async componentWillMount(){
    await this.getLocation();
    await this.getWeather();
  }

我的getLocation函数:

async getLocation() {
    navigator.geolocation.getCurrentPosition(
      (position) => {
        this.setState({
          latitude: position.coords.latitude,
          longitude: position.coords.longitude,
          error: null,
        });
      },
      (error) => this.setState({ error: error.message }),
      { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },
    );
  }

getWeather功能:

async getWeather() {
    try{
      let url = 'https://api.openweathermap.org/data/2.5/weather?lat=' + this.state.latitude + '&lon=' + this.state.longitude + '&appid=<my app id>&units=metric'
      console.log(url);
      fetch(url).then(res=>res.json())
      .then(json=>{
        console.log(url);
        this.setState({
          weather: {
            city: json.name,
            temperature: json.main.temp,
            wind: {
              direction: json.wind.direction,
              speed: json.wind.speed          
            }
          }
        });
      });
    }
    catch(error){
      console.log(error)
    }
  }

从API获得的json:

{  
   "coord":{  
      "lon":6.14,
      "lat":52.79
   },
   "weather":[  
      {  
         "id":804,
         "main":"Clouds",
         "description":"overcast clouds",
         "icon":"04d"
      }
   ],
   "base":"stations",
   "main":{  
      "temp":11.49,
      "pressure":996,
      "humidity":81,
      "temp_min":11,
      "temp_max":12
   },
   "visibility":10000,
   "wind":{  
      "speed":8.2,
      "deg":240
   },
   "clouds":{  
      "all":90
   },
   "dt":1543829100,
   "sys":{  
      "type":1,
      "id":1530,
      "message":0.1147,
      "country":"NL",
      "sunrise":1543822083,
      "sunset":1543850543
   },
   "id":2746766,
   "name":"Steenwijk",
   "cod":200
}

getWeather函数中的控制台日志将纬度和经度记录为“ NULL”。我认为这是因为尚未完成getLocation函数。我不知道如何使它工作。

0 个答案:

没有答案