TypeError: Cannot read property 'country' of undefined
TypeError: Cannot read property 'country' of undefined
我正在尝试从 API 获取数据并在我的应用程序中使用该数据。但问题是,当我尝试从 JSON 中获取某些对象或数据时,我刚刚从 API 中获取,我得到 TypeError: Cannot read 属性 'country' 未定义.
属性 DO 存在。
顺便说一下,我正在使用 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";
// function
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, longtitude) {
const One_weather_call = await fetch(`https://community-open-weather-map.p.rapidapi.com/weather?lat=${latitude}&lon=${longtitude}&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 (
<React.Fragment>
<Navigation city={this.state.responseFromAPI.name}
country={this.state.responseFromAPI.sys.country}
/>
</React.Fragment>
);
};
}
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
.
等其他变量时没有错误
最后,我设法通过有条件地为 render()
函数中的组件设置道具来解决问题,如下所示:
render() {
return (
<React.Fragment>
<Navigation city={this.state.responseFromAPI ? this.state.responseFromAPI.name : ""}
country={this.state.responseFromAPI ? this.state.responseFromAPI.sys.country
: "Loading"}
/>
</React.Fragment>
);
};
我正在尝试从 API 获取数据并在我的应用程序中使用该数据。但问题是,当我尝试从 JSON 中获取某些对象或数据时,我刚刚从 API 中获取,我得到 TypeError: Cannot read 属性 'country' 未定义.
属性 DO 存在。
顺便说一下,我正在使用 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";
// function
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, longtitude) {
const One_weather_call = await fetch(`https://community-open-weather-map.p.rapidapi.com/weather?lat=${latitude}&lon=${longtitude}&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 (
<React.Fragment>
<Navigation city={this.state.responseFromAPI.name}
country={this.state.responseFromAPI.sys.country}
/>
</React.Fragment>
);
};
}
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
.
最后,我设法通过有条件地为 render()
函数中的组件设置道具来解决问题,如下所示:
render() {
return (
<React.Fragment>
<Navigation city={this.state.responseFromAPI ? this.state.responseFromAPI.name : ""}
country={this.state.responseFromAPI ? this.state.responseFromAPI.sys.country
: "Loading"}
/>
</React.Fragment>
);
};