Я получаю эту ошибку при вызове 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)
}
}
JSON, который вы получаете из API:
{
"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 еще не завершена.Я понятия не имею, что делать, чтобы это работало.