如何解决来自api的json数据的react-table v7动态列和行
我是新手。我有一个 json api,需要在客户端显示为表格。我想使用 react-table v7。我的想法是:
- 将数据中的键作为列标题和访问器
- json 数据是行
import React from 'react';
import { useTable } from 'react-table'
const Table = ({
headers,items
}) => {
function getColumns() {
if (headers) {
return headers.map(key => {
return {
Header: key.toString(),accessor: key.toString()
};
});
}}
const columns = React.useMemo(() => [
getColumns()
],[]
)
const data = React.useMemo(() => [
items
],[]
)
const {
getTableProps,getTableBodyProps,headerGroups,rows,prepareRow,} = useTable({ columns,data })
return (
<table {...getTableProps()} style={{ border: 'solid 1px blue' }}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th
{...column.getHeaderProps()}
style={{
borderBottom: 'solid 3px red',background: 'aliceblue',color: 'black',fontWeight: 'bold',}}
>
{column.render('Header')}
</th>
))}
</tr>
))}
</thead>
<tbody {...getTableBodyProps()}>
{rows.map(row => {
prepareRow(row)
return (
<tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<td
{...cell.getCellProps()}
style={{
padding: '10px',border: 'solid 1px gray',background: 'papayawhip',}}
>
{cell.render('Cell')}
</td>
)
})}
</tr>
)
})}
</tbody>
</table>
)
}
export default Table;
然后我有另一个组件通过 axios 发出获取请求并从其响应中设置列和数据并导入 Table 组件以传递此处定义的道具,代码如下:
import React,{ useEffect,useState } from 'react'
import Table from './Table'
import axios from 'axios'
export const STable = () => {
const [columns,setColumns] = useState([])
const [rows,setRows] = useState([])
const getData = () => {
axios.get("http://localhost:5001/")
.then(res => {
console.log(res.data)
setColumns({ columns: Object.keys(res.data[0]) })
setRows({ rows: res.data })
})
.catch(error => {
console.log(error)
})
}
useEffect(() => {
getData()
},[] )
return (
<div>
<Table headers={columns} items={rows} />
</div>
)
}
export default Stable;
最后是应用组件
import React from 'react';
import STable from './components/STable';
function App() {
return (
<div>
<STable/>
</div>
);
}
export default App;
我不知道我哪里做错了。我将不胜感激。
解决方法
您需要在所有带有访问器的列中都有 id 字段。在您的代码中,您需要为每个内部列设置 id 字段。
return headers.map(key => {
return {
id: key toString(),Header: key.toString(),accessor: key.toString()
};
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。