下面是使用 react-table 节点包 BasicTable.js 完成的表格组件
import { useTable, usePagination } from "react-table";
import React, { useEffect, useMemo, useState } from "react";
import { COLUMNS } from "./postColumns";
import "./BasicTable.css";
const BasicTable = () => {
let [res, setRes] = useState([]);
useEffect(() => {
const loadData = async () => {
try {
const res = await fetch(
"https://jsonplaceholder.typicode.com/comments"
);
const data = await res.json();
return data;
} catch (err) {
console.log(err);
}
};
loadData().then((data) => setRes(data));
}, []);
for (let k = 0; k < res.length; k++) {
if (res[k].body.length > 150) {
res[k].body = res[k].body.substring(0, 150) + "...";
}
}
const columns = useMemo(() => COLUMNS, []);
const data = useMemo(() => res, [res]);
console.log(data);
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
page,
pageOptions,
nextPage,
previousPage,
canNextPage,
canPreviousPage,
footerGroups,
} = useTable({ columns, data }, usePagination);
return (
<>
<table {...getTableProps()}>
<thead>
{headerGroups.map((headerGroup) => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((header) => (
<th {...header.getHeaderProps()}>{header.render("Header")}</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{page.map((row) => {
prepareRow(row);
return (
<tr {...row.getRowProps()}>
{row.cells.map((cell) => (
<td {...cell.getCellProps()}>{cell.render("Cell")}</td>
))}
</tr>
);
})}
</tbody>
<tfoot>
{footerGroups.map((footerGroup) => (
<tr {...footerGroup.getFooterGroupProps()}>
{footerGroup.headers.map((header) => (
<td {...header.getFooterProps()}>{header.render("Footer")}</td>
))}
</tr>
))}
</tfoot>
</table>
<div className="buttons">
<button onClick={previousPage} disabled={!canPreviousPage}>
Prev Page
</button>
<button onClick={nextPage} disabled={!canNextPage}>
Next Page
</button>
</div>
</>
);
};
export default React.memo(BasicTable);
react-table 中使用的 Column.js 文件
export const COLUMNS = [
{
Header: "postId",
Footer: "postId",
accessor: "postId",
},
{
Header: "id",
Footer: "id",
accessor: "id",
},
{
Header: "name",
Footer: "name",
accessor: "name",
},
{
Header: "email",
Footer: "email",
accessor: "email",
},
{
Header: "body",
Footer: "body",
accessor: "body",
},
];
如果我们没有从 https://jsonplaceholder.typicode.com/comments获取数据,我们会在 const data = useMemo(() => res, [res]); 我想显示一条消息说没有记录而不是表格怎么做