我在我的React应用程序中有一个函数,它可以迭代JSON API的响应数组,它可以与数组"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}]
正常工作:
render() {
const persons = this.state.person.map((item) => {
return <div>
<h1>{item['id']}</h1>
<span>{item['name']}</span>
</div>
}
}
但如何为对象遍历创建相同的功能呢?如果 this.state.person
是这样的东西,而我想要读取 coord['lon']
:
{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"base":"stations","main":{"temp":280.32,"pressure":1012,"humidity":81,"temp_min":279.15,"temp_max":281.15},"visibility":10000,"wind":{"speed":4.1,"deg":80},"clouds":{"all":90},"dt":1485789600,"sys":{"type":1,"id":5091,"message":0.0103,"country":"GB","sunrise":1485762037,"sunset":1485794875},"id":2643743,"name":"London","cod":200}
由于
map
函数仅适用于数组,因此我遇到了这个错误:this.state.person.map is not a function TypeError
编辑(添加完整代码)
class App extends React.Component {
constructor(props){
super();
this.state = {
person: [],
cityName: 'London'
};
}
componentDidMount() {
this.UserList();
}
update(e){
this.setState({cityName: e.target.value})
}
UserList(city = this.state.cityName){
let weatherURL = 'http://api.openweathermap.org/data/2.5/weather?q=London&appid=c24bda9c5812d6be82860b70c35d41a5';
return $.getJSON(weatherURL).then((response) => {this.setState({person: response.coord})});
}
render() {
const persons = this.state.person.map((item) => { // it gives me TypeError,
return <div>
<h1>{item[0]}</h1>
<span>{item[1]}</span>
</div>
});
return <div id="layout-content" className="layout-content-wrapper">
<input type="text"
onChange={this.update.bind(this)}/>
<div className="panel-list">{ persons }</div>
</div>
}
}
export default App;
它因为map函数返回一个TypeError错误。
this.state
的完整JSON表示。您发布的内容毫无意义 - 您声称在"wheather":
属性中有一个数组,但正在访问this.state.person
? - Bergiperson:[ ]
和“coord”:{"lon":-0.13,“lat”:51.51}
不是我理解中的数组。 - Denyscoord
对象做什么?是的,你不能迭代它。只需访问this.person.coord.lon
。 - BergisetState({coord: response.coord})
并渲染this.state.coord.lon
(无需任何映射)即可。如果您还想显示天气,请使用单独的state
属性实现。 - Bergi