javascript - TypeError:无法读取未定义的属性“国家”
问题描述
我正在尝试从 API 获取数据并在我的应用程序中使用该数据。但问题是当我尝试从我刚刚从 API 获得的 JSON 中获取某些对象或数据时,我得到TypeError: Cannot read property 'country' of undefined。
该属性确实存在。
顺便说一句,我正在使用 React.js。
我非常感谢您的帮助和指导。
这是代码:
应用程序.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>
);
};
推荐阅读
- android - 如何跳过名称中包含“单词 A”的所有任务?
- r - ifelse在R中有两个条件数字和分类
- python - 有没有办法在 Python 中运行 for 循环而不必将列表传递给它?
- lucene - 如何对 Lucene 查询的结果进行分组,按组计算命中并突出显示某些选定组中的文档?
- typescript - transpileOnly 时 ts-loader 时间超慢:假?
- react-native - 将 react-native 中的多个 html-tags 替换为 Text
- javascript - 分配中的左侧无效,但我正在尝试分配一个变量
- c++ - msvc++ 和 clang 怎么知道这个结构的大小,甚至不需要前向声明?
- pandas - how remove spaces from a dataframe separated by ,
- android - Xamarin Android Webview:getUserMedia 无法打开相机