我是新来的反应。我有一个 json api,我需要在客户端显示为表格。我想使用 react-table v7。我的想法是:
- 将数据中的键作为列 Headers 和 Accessor
- 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;
最后是 App 组件
import React from 'react';
import STable from './components/STable';
function App() {
return (
<div>
<STable/>
</div>
);
}
export default App;
但是我收到此错误,请参见图片,
我不知道我在哪里做错了。我将不胜感激任何帮助。