如何解决TypeError:无法读取未定义的属性“国家”
我正在尝试从API提取数据并在我的应用中使用该数据。但是问题是当我尝试从API刚得到的JSON中获取某些对象或数据时,出现 TypeError:无法读取未定义的属性'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>
);
};
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。