TypeError: Cannot read property 'country' of undefined
TypeError: Cannot read property 'country' of undefined
我正在尝试从API获取数据并在我的应用程序中使用该数据。但问题是,当我尝试从刚刚从API获取的JSON中获取特定对象或数据时,我会得到以下错误:TypeError: Cannot read property 'country' of undefined。
这个属性确实存在。
顺便说一下,我正在使用React.js。
非常感谢您的帮助和指导。
以下是代码:
App.js
import React, { useEffect, useState } from 'react'; import './App.css'; import Navigation from "./components/Navigation/Navigation"; import Forecast from "./components/forecast/forecast"; class App extends React.Component { constructor(props) { super(props); this.state = { responseFromAPI: {}, } } getPosition = function () { return new Promise(function (resolve, reject) { navigator.geolocation.getCurrentPosition(resolve, reject); }); } getWeather = async function (latitude, longitude) { const One_weather_call = await fetch(`https://community-open-weather-map.p.rapidapi.com/weather?lat=${latitude}&lon=${longitude}&units=metric`, { "method": "GET", "headers": { "x-rapidapi-host": "some private info here", "x-rapidapi-key": "some private info here" } }).then(response => response.json()); console.log("fetch data"); return One_weather_call; }; componentDidMount() { this.getPosition() .then(position => { this.getWeather(position.coords.latitude, position.coords.longitude) .then(res => { this.setState({ responseFromAPI: res }); }); }); console.log("after setting response in app.js ", this.state.responseFromAPI); }; render() { return (); }; } export default App;
JSON数据
{
"coord": { "lon": 139,"lat": 35},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 281.52,
"feels_like": 278.99,
"temp_min": 280.15,
"temp_max": 283.71,
"pressure": 1016,
"humidity": 93
},
"wind": {
"speed": 0.47,
"deg": 107.538
},
"clouds": {
"all": 2
},
"dt": 1560350192,
"sys": {
"type": 3,
"id": 2019346,
"message": 0.0065,
"country": "JP",
"sunrise": 1560281377,
"sunset": 1560333478
},
"timezone": 32400,
"id": 1851632,
"name": "Shuzenji",
"cod": 200
}
正如您所看到的,这个JSON数据中的国家属性是以json.sys.country
的方式放置的,但是我通过这种方式获取时会出错。但是,当我尝试访问其他变量,如json.main
时,却没有错误。