reactjs - 如何在 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;
解决方案
你可以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 因为它不仅代表第一个项目,而且代表当前项目(这不是代码工作所必需的,只是一个好主意)
推荐阅读
- node.js - 如何使用firebase函数返回保存在firebase存储中的文件的json内容
- git - git fetch:如何查看每个分支的下载数据
- r - 过滤在 r 中事件“A”的时间范围内发生的事件
- javascript - 有没有办法在输入之前修改搜索菜单以隐藏菜单?
- laravel - 在 Laravel 中,我应该将模型的实用程序放在哪里?
- javascript - 有没有办法发出 API 请求,并且在发出请求之前只获取满足特定条件的数据?
- ios - MKUserTrackingButton 仅在长按时响应
- jsf - JSF 2.3 MetaTagHandler 未处理类型 com.sun.faces.cdi.CdiValidator 错误
- laravel - 使用 Event::fake() 或 Queue::fake() 时通知测试失败
- bootstrap-4 - 文本和图像与引导程序并排