首页 > 解决方案 > 如何在 React 中访问嵌套数组对象

问题描述

我需要从列表数组中显示“详细信息”数组。如何使用 map() 函数正确访问它?

使用 list.map() 我可以映射第一级项目,但找不到第二级数组的解决方案。

输出可以如下:

约翰一书, 18, 180

2 唐, 20, 170

3 怀特先生,28 岁,170 岁

代码:

import React, { Component } from 'react';
 
class App extends Component {
  constructor(props) {
    super(props);
 
    this.state = {
        list: [
        {
        id:1, 
        name:'John', 
        details: [
            {
                id:1, 
                age:18, 
                height:180
            }
        ]
        },

        {
        id:2,
        name:'Don',
        details: [
            {
                id:3, 
                age:20, 
                height:170
            }
        ]
        },
  
        {
        id:3,
        name:'Mr White', 
        details: [
            {
            id:3, 
            age:28, 
            height:190
            }
        ]
        }
        ],
      };
    }
 
  render() {
    return (
      <div>
        <ul>
          {this.state.list.map((item1) => (
            <p key={item1.id}>{item1.id} {item1.name}</p>
          ))}
        </ul>
      </div>
    );
  }
}
 
export default App;

标签: reactjs

解决方案


你可以map在第一个里面嵌套一个map

{this.state.list.map((item1) => (
    <>
        <p key={item1.id}>{item1.id} {item1.name}</p>
        {item1.details.map(detail => (
            <p>{detail.age} {detail.height}</p>
        ))}
    </>
))} 

您需要将元素包装在<></>标签中,因为您只能从速记函数返回一个元素。

您可能还想重命名item1为 item 因为它不仅代表第一个项目,而且代表当前项目(这不是代码工作所必需的,只是一个好主意)


推荐阅读