来自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;

但是我收到此错误,请参阅图片

enter image description here

我不知道我哪里做错了。我将不胜感激。

解决方法

您需要在所有带有访问器的列中都有 id 字段。在您的代码中,您需要为每个内部列设置 id 字段。

return headers.map(key => {
      return {
        id: key toString(),Header: key.toString(),accessor: key.toString()
      };
    });