javascript - React JS如何在数组内显示带有数组的JSON
问题描述
我有一个 MongoDB 查询,它返回 JSON,如下所示:
{
_id: 'New List',
listItems: [
{
_id: '5b86ef7dfb6fc03893e56a54',
name: 'Coffee',
quantity: '5',
listName: 'New List',
urgency: 'High'
}
]
},
{
_id: 'My List',
listItems: [
{
_id: '5b8552ed32f03600146b82e5',
quantity: 1,
listName: 'My List',
urgency: 'Normal',
name: 'Tea bags',
date: '2018-08-28T13:49:33.615Z',
__v: 0
},
{
_id: '5b855b9e3fcbc00014a11a4d',
quantity: 1,
listName: 'My List',
urgency: 'Normal',
name: 'Cold Sore Medicine',
date: '2018-08-28T14:26:38.705Z',
__v: 0
},
{
_id: '5b85b5daec7c4008f4294977',
quantity: 1,
listName: 'My List',
urgency: 'Normal',
name: 'School Bag(Satchel)',
date: '2018-08-28T20:51:38.993Z',
__v: 0
},
{
_id: '5b85b6246c915f0014dfa961',
quantity: 1,
listName: 'My List',
urgency: 'Normal',
name: 'School Uniform',
date: '2018-08-28T20:52:52.227Z',
__v: 0
}
]
}
我正在尝试使用 reactstrap 在 listgroup 元素中使用 react 来显示它。查询按“listName”分组,我想显示按 listName 组织的列表。
下面是似乎不起作用的代码。
render() {
const { items } = this.props.item;
if (items) console.log("items: " + items.toString())
return (
<Container>
<ListGroup>
<TransitionGroup className="shopping-list">
{items.map(({ listItems }) => (
<ListGroupItem>
{listItems}
</ListGroupItem>
listItems.map((eachThing) =>
<ListGroupItem>
{eachThing.name} | {eachThing.quantity} | {eachThing.listName}
</ListGroupItem>
)))}
</TransitionGroup>
</ListGroup>
</Container>
)
}
下面是编译代码的错误:
Syntax error: Unexpected token, expected , (34:0)
[1]
[1] 32 | </ListGroupItem>
[1] 33 |
[1] > 34 | listItems.map((eachThing) =>
[1] | ^
[1] 35 | <ListGroupItem>
[1] 36 | {eachThing.name} | {eachThing.quantity} | {eachThing.listName}
[1] 37 | </ListGroupItem>
任何帮助将不胜感激。
解决方案
使用@charlietfl 的评论并根据您要实现的目标进行一些编辑,您的整个代码应该是
render() {
const { items } = this.props.item;
if (items) console.log("items: " + items.toString())
return (
<Container>
<ListGroup>
<TransitionGroup className="shopping-list">
{items.map(({ listItems }) => (
<ListGroupItem>
{listItems.map((eachThing) =>
<ListGroupItem>
{eachThing.name} | {eachThing.quantity} | {eachThing.listName}
</ListGroupItem>
)}
</ListGroupItem>
))}
</TransitionGroup>
</ListGroup>
</Container>
)
}
推荐阅读
- java - 当 split() 函数将字符串正确拆分为模式时,为什么 matches() 函数返回 false ?
- angular - 我想只使用一个输入字段以 6 角形式创建一个单选按钮
- java - 使用 Gson 自定义 Json 序列化
- jquery - 固定侧边栏菜单不跳转到正确的位置
- java - 与集合和泛型相关的 Java 10 迁移问题
- python - 在大型 ZIP 文件中导入 Python 包
- c# - 从桌面客户端调用 Web API
- microsoft-teams - 如何在 ASP.NET 核心中验证从 Microsoft Teams 发送的消息有效负载?
- javascript - 使用 set-Attribute 设置 ng-pattern 不起作用
- html - 如何将html表单数据解析成文档