我是React和JS的新手。尝试使用react-table并将数据从类发送到函数。来自props的数据显示在控制台中,但不显示在react-table中。下面是console.log的代码和结果。请告诉我我的错误以及我要改进的主题。
注意:如果替换此行:
const result = props.state;
具有:
const result = props.state.data;
显示错误data is undefined
。
function Showdata(props){
// 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>
)
}
答案 0 :(得分:0)
我在您的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。