我是React和JS的新手。尝试使用react-table并将数据从类发送到函数。来自props的数据显示在控制台中,但不显示在react-table中。以下是console.log的代码和结果。请告诉我我的错误以及我要改进的主题。
注意:如果替换此行const结果= props.state;与const结果= props.state.data;显示错误“数据未定义”。
// Result of below console.log is in attached image.
console.log(props.state.data);
const columns = useMemo(
() => [
{
Header: 'Column 1',
accessor: 'props.state.data.id', // accessor is the "key" in the data
},
{
Header: 'Column 2',
accessor: 'props.state.data.TeamName',
},
],
[]
);
const [data, setData] = useState([]);
useEffect(() => {
(async () => {
/*If replace below line with const result = props.state.data; show error "data is undefined".*/
const result = props.state;
setData(result.data);
console.log(result.data);
})();
}, []);
return (
<div className="App">
<Table columns={columns} data={data} />
</div>
);
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({ columns, data });
return (
<div>
<p>Data of {props.state.category}</p>
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<th {...column.getHeaderProps()}>{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()}>{cell.render('Cell')}</td>
})}
</tr>
)
})}
</tbody>
</table>
</div>
)
}```
[![Result of console log][1]][1]
[1]: https://i.stack.imgur.com/cQeaz.jpg
我在您的columns
中看到错误:
const columns = useMemo(
() => [
...
accessor: 'props.state.data.id',
...
accessor: 'props.state.data.TeamName',
...
);
不能有accessor
像props.state.data.id
。在您的控制台中,我看到了一系列数据对象,例如:
[{ id: ..., TeamNameL ... }]
并且您应该给此字段类似:
const columns = useMemo(
() => [
...
accessor: 'id',
...
accessor: 'TeamName',
...
);
也可以看到官方的example。