首页 > 解决方案 > 使用嵌套的 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;

标签: arraysjsonreactjsdatatablenested

解决方案


在您的渲染方法中,您可以执行以下操作:

<td>{info.Tags.filter(env => env.Key === "env").map(e => e.Value).join(' ')}</td>

因此,您不必将地图中的返回值td包装在标签中,而是将整个内容包装在标签中。


推荐阅读