首页 > 解决方案 > 使用 JSON 反应生成表

问题描述

我有一个 API 端点,它会像这样返回我的 Google 表格数据:

[{'App Id': '1', 'Name': 'Test', 'Homepage': 'example.com'}, {'App Id': '2', 'Name': 'Another', 'Homepage': 'example.org'}]

我正在axios使用以下代码获取上面的数据。

axios.get('http://127.0.0.1/')
  .then((response) => {
    console.log(response.data);
  });

我想用 React 中的数据制作一个表格。该表应如下所示:

| App Id | Name    | Homepage    |
|--------|---------|-------------|
| 1      | Test    | example.com |
| 2      | Another | example.org |

如何使这些数据看起来像上表?

标签: javascriptreactjsrest

解决方案


因此,正如所讨论的,您需要使用从其余 api 获得的数据来构建表

在这里,您可以将列设为静态

应用程序.js

import React, { useState, useEffect, Fragment } from "react";
import "./styles.css";
import axios from "axios";

export default function App() {
  const [data, setData] = useState([]);

  const columns = [
    { property: "id", header: "Id" },
    { property: "title", header: "Title" }
  ];

  useEffect(() => {
    const loadData = async () => {
      const response = await axios(
        "https://jsonplaceholder.typicode.com/todos/"
      );
      setData(response.data);
    };
    loadData();
  }, []);

  return (
    <Fragment>
      <table>
        <tr>
          {columns.map(col => (
            <th>{col.header}</th>
          ))}
        </tr>
        {data.map(datumn => {
          return (
            <tr>
              {columns.map(col => {
                return <td>{datumn[col.property]}</td>;
              })}
            </tr>
          );
        })}
      </table>
    </Fragment>
  );
}

样式.css

table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td,
th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}

示例代码框

您可以通过添加错误和加载状态即兴创作。


推荐阅读