【问题标题】:Render a nested array of objects in react在反应中渲染嵌套的对象数组
【发布时间】:2017-07-29 16:42:19
【问题描述】:

我映射多个对象。 [{name:"y", country:"US", cities:[obj,obj,ob]},{name:"y", country:"US", cities:[obj,obj,ob]}]

如何嵌套循环,以便首先遍历对象,然后遍历(在此示例中)城市?谢谢!!

没有嵌套外观的渲染函数如下所示:

render() {
  const persons = this.state.name.map((item, i) => {
    return (
      <div>
        <h5> {item.name} </h5> 
        <h5> {item.country} </h5> 
        //here I would like to show the cities
      </div>
    );
  });
  return (
    <div>
      <div className = "panel-list"> 
        All: {persons} 
      </div> 
    </div>
  );
}

城市对象示例:

[{visitors:34, rating:4}, 
 {visitors:1234, rating:1},
 {visitors:124, rating:2}]

【问题讨论】:

    标签: javascript reactjs loops


    【解决方案1】:

    您可以使用嵌套映射来映射内部子对象以及

         render() {
                const persons = this.state.name.map((item, i) => {
                    return (
                       <div>
                          <h5> {item.name} </h5> 
                          <h5> {item.country} </h5> 
                          <h4>{item.cities.map((city) => {
                                 return (<li>{/* city object details here*/}</li>)
                           })}</h4>
                       </div>);
                });
                return (
                <div>
                    <div className = "panel-list"> 
                        All: {persons} 
                    </div> 
                </div>
                  );
            }
    

    【讨论】:

    • 感谢您的回答。如果我使用您的解决方案,我会得到错误的结果。可以说我(例如)5个国家。每个国家有5个城市。然后我会得到法国加上所有 5 个国家的所有城市,而不仅仅是一个
    • 根据您的数据对象{name:"y", country:"US", cities:[obj,obj,ob]} 城市是美国国家内的城市,是吗?你的城市对象是什么样子的。我想你也需要在你的问题中添加它
    • 我用国家对象编辑了我的问题。所以如果我这样做

      {city.visitor}

      我不会按国家/地区获得,但它看起来像法国,(访问者)34,1234,124
    • 在您的问题中,该对象包含名称国家和城市,但不包含国家/地区见{name:"y", country:"US", cities:[obj,obj,ob]}
    • 对不起,这是一个类型,意思是城市而不是国家
    猜你喜欢
    • 2022-01-25
    • 2020-08-29
    • 1970-01-01
    • 2023-02-16
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多