javascript - 如何遍历这些数据以从中获取信息
问题描述
我正在调用天气 api,它以数据响应。我能够从对象中获取一些数据,但是当我尝试获取某些数据时,它在 React 中给了我对象错误。
class Weather extends React.Component{
constructor(props){
super(props);
this.state = {
weatherData: []
}
}
componentDidMount() {
axios.get(`https://api.openweathermap.org/data/2.5/weather?q=Brampton,ca&units=metric&mode=json`)
.then(res => {
const weatherData = res.data;
this.setState({ weatherData });
})
}
render(){
return(
<div>
WetherData<br/>
{JSON.stringify(this.state.weatherData)}
<ul>
<li>{this.state.weatherData.name}</li>
<li>{JSON.stringify(this.state.weatherData.weather)}</li>
</ul>
</div>
)
}
}
ReactDOM.render(<Weather />, document.getElementById('app'))
原始数据
"coord":{"lon":-79.76,"lat":43.69},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04d"}],"base":"stations","main":{"temp":10.06,"pressure":1017,"humidity":81,"temp_min":7.78,"temp_max":12.22},"visibility":24140,"wind":{"speed":4.1,"deg":10},"clouds":{"all":90},"dt":1556908224,"sys":{"type":1,"id":1002,"message":0.0067,"country":"CA","sunrise":1556878127,"sunset":1556929377},"id":5907364,"name":"Brampton","cod":200}
{JSON.stringify(this.state.weatherData.weather)} 我在这里获取数据。
但是当我尝试
{JSON.stringify(this.state.weatherData.weather.main)} 它给了我对象错误。
或者如果我尝试
{JSON.stringify(this.state.weatherData.coord)} 有效
但
{JSON.stringify(this.state.weatherData.coord.lon)} 给我一个对象错误
解决方案
推荐阅读
- reactjs - React,componentWillReceive lifeCycle Hook 未被调用(在传递道具时)
- python - 如何正确设置 STANFORD_MODELS VARIABLE?
- sql - 如何在 sql server(或 asp.net)中创建或生成此模式以供参考 ID
- google-search-console - 为什么我的“发现当前未编入索引”链接的数量增加了?
- python - 如何确定使用 Selenium 和 Python 在网页上查找和打开所有配置文件的确切 xpath 是什么?
- git - Git checkout 到新分支不会刷新索引和工作目录的内容
- css - 用 AngularJS 改变 CSS
- java - Apereo Cas - 自定义主体 ID 发布
- c++ - 如何调用包含标题的函数?
- image - 检查图像是否包含文字