小编典典

在react中渲染嵌套的对象数组

reactjs

我映射了多个对象。 [{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}]

阅读 400

收藏
2020-07-22

共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>
              );
        }
2020-07-22