【发布时间】:2018-12-10 12:53:46
【问题描述】:
我正在尝试从 JSON 之后的“天气”表单中获取项目“图标”
{
"coord": {
"lon": 14.33,
"lat": 49.94
},
"weather": [{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}]
}
我不知道如何通过渲染方法提取数组中的项目。 我的代码是:
class Weather extends React.Component {
constructor() {
super();
this.state = {
'items': []
}
}
componentDidMount() {
this.getItems();
}
getItems() {
fetch('http://api.openweathermap.org/data/2.5/weather?lat=49.9415967&lon=14.3316786&appid=ed62e370682cc9e4144620905eff37e4')
.then(results => results.json())
.then(results => this.setState ({'items': results}));
}
render() {
return (
<div>
<h1>here should be an icon..</h1>
{this.state.items.weather.map(function(weather, index) {
return <h3 key={index}>{weather.icon}</h3>
})}
</div>
);
}
}
我实际上在这里使用了这个问题:Get access to array in JSON by ReactJS ...这让我走到了这一步,但仍然无法使其正常工作...
【问题讨论】:
-
正如@Tholle 指出的那样,您应该在项目中添加天气键,或者如果您只关心天气,您可以将状态与项目键作为数组并在设置状态时,只需这样做
this.setState({ 'items': results.weather }) -
在这种情况下,它只是 console.logs undefined...