arrays - 使用嵌套的 JSON 数据渲染反应表
问题描述
我有一个嵌套的 JSON,我试图将它呈现到一个表中。这个想法是通过遍历 JSON 来填充。我的问题是当我遍历标签并尝试填充环境列时。如果密钥存在,它工作正常,但如果密钥不存在,它会将 TD 转移到前一列。
例如,在下图中,您可以在第一行看到web to ENV 列,而不是 Purpose 列。对于其他两个,由于密钥存在,因此表格呈现良好。
import React, { Component } from "react";
import { Table } from "reactstrap";
class Example extends Component {
state = {
data: [
{
id: "1",
States: "many",
Purpose: "web",
Tags: [
{
Key: "Name",
Value: "server1"
}
]
},
{
id: "2",
States: "Single",
Purpose: "App",
Tags: [
{
Key: "Name",
Value: "server2"
},
{
Key: "env",
Value: "qa"
}
]
},
{
id: "3",
States: "None",
Purpose: "DB",
Tags: [
{
Key: "env",
Value: "qa"
},
{
Key: "Name",
Value: "server3"
}
]
}
]
};
render() {
let envs;
return (
<Table className="align-items-center table-flush" responsive>
<thead className="thead-light">
<tr>
<th scope="col">ID</th>
<th scope="col">States</th>
<th scope="col">Env</th>
<th scope="col">Purpose</th>
</tr>
</thead>
<tbody>
{this.state.data.map(info => (
<tr>
<th scope="row">{info.id}</th>
<td>{info.States}</td>
{info.Tags.filter(env => env.Key === "env").map(e => (
<td>{e.Value}</td>
))}
<td>{info.Purpose}</td>
</tr>
))}
</tbody>
</Table>
);
}
}
export default Example;
解决方案
在您的渲染方法中,您可以执行以下操作:
<td>{info.Tags.filter(env => env.Key === "env").map(e => e.Value).join(' ')}</td>
因此,您不必将地图中的返回值td
包装在标签中,而是将整个内容包装在标签中。
推荐阅读
- python - 什么是两个并行映射和映射到值差异的元组
- realm - 缺少领域构造函数
- c++ - 自动为 Qt 配置套件
- node.js - 为 PostgreSQL 创建 Node.js 服务:一个 json-patch 运行器
- c++ - 我怎样才能使它更有效率?我正在尝试重构我的程序,有什么方法可以使它更有效?
- c# - Docusign:请求的权限不正确
- javascript - 如何保存 webpack-dev-server 更改?
- javascript - 如何使用 React 中的参数访问过滤器内的道具
- sql - ORA-40478-即使返回 clob 时输出值也太大(最大值:4000)
- javascript - 为什么在另一个函数中使用时会出现“未捕获的 TypeError:regex.test 不是函数”?