在React中迭代JSON对象

3

我在我的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 - Bergi
@Bergi,问题在于person:[ ]“coord”:{"lon":-0.13,“lat”:51.51}不是我理解中的数组。 - Denys
你想对 coord 对象做什么?是的,你不能迭代它。只需访问 this.person.coord.lon - Bergi
只需使用 setState({coord: response.coord}) 并渲染 this.state.coord.lon(无需任何映射)即可。如果您还想显示天气,请使用单独的 state 属性实现。 - Bergi
@Bergi 谢谢!它有效! - Denys
显示剩余4条评论
2个回答

0

只需将完整的响应存储在状态值中,然后访问特定属性。

假设您将完整响应存储在变量data中,那么要访问lon值,请使用data.coord.lon,如果您想要循环遍历天气,请像这样使用:

data.weather.map(item => console.log(item.main))

请查看此示例:

let data = {
 "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
}

console.log('coord', data.coord.lon);

data.weather.map(item=>{
 console.log(item.main)
})


0

如果您想对任意对象进行映射,应使用Object.keys函数。当在对象上调用时,它将返回一个包含对象所有属性键的数组。然后,您可以使用mapforEach在此数组上进行迭代。

例如:

const person = this.state.person
const personKeys = Object.keys(person)

personKeys.map(key => do_something_with(key))

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接