javascript - 使用 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 |
如何使这些数据看起来像上表?
解决方案
因此,正如所讨论的,您需要使用从其余 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;
}
示例代码框
您可以通过添加错误和加载状态即兴创作。
推荐阅读
- c++ - 对于自定义 FFmpeg I/O API:关于 avio_alloc_context() 的 write_packet 回调函数的数据不正确
- python - 正则表达式查找关键字并打印匹配的整行
- azure - Azure Devops Pipeline 构建失败无法解析此引用无法找到程序集
- google-site-verification-api - Google Site Verification api 错误 - 'verification_type 的值无效
- vue.js - 二重奏选择器的dueChange事件不适用于Ionic 5 / Vue 3
- kubernetes - Kubernetes 中的 APOC UUID 支持
- angular - 元素属性_ngcontent键每次刷新
- javascript - 如何让 Combobox onSelect 在 React Bootstrap 模式上工作?
- javascript - Send Grid Email Api 正在发送电子邮件 3 次
- android - 改造 2 POST JSON 对象,响应给出错误代码 400,消息 = nul