我正在尝试使用 react-table 并引发错误。当我运行它时,它会在屏幕上显示以下堆栈跟踪:
它似乎试图从列创建映射,但由于列未定义而引发错误。
我将它传递给我的专栏,但也许我做得不对。
这是我的代码:
class Blog extends Component {
...
createTable() {
return this.state.blogPosts.length ? <Table posts={this.state.blogPosts} /> : null;
}
...
componentDidMount() {
...
axios.get('/blogs').then(response => {
if (response.data) {
const entries = Object.entries(response.data);
this.setState({blogPosts: entries.map(p => Object.assign({id: p[0]}, {...p[1]}))
.sort((p1, p2) => p1.updatedAt > p2.updatedAt ? -1 : 1)});
}
}, err => {
console.log('err=', err);
});
}
}
import React from 'react';
import {
useTable,
useGroupBy,
useFilters,
useSortBy,
useExpanded,
usePagination
} from 'react-table';
function Table(props) {
const cols = React.useMemo(() => [
{
Header: 'title',
accessor: 'titleCol'
},
{
Header: 'body',
accessor: 'bodyCol'
},
{
Header: 'last updated',
accessor: 'updatedAtCol'
}
], []);
const dataArray = [];
for (var index = 0; index < props.posts.length; index++) {
const post = props.posts[index];
dataArray.push({
titleCol: post.title,
bodyCol: post.body,
updatedAtCol: post.updatedAt
});
}
const data = React.useMemo(() => dataArray, []);
const {
getTableProps,
getTableBodyProps,
headerGroups,
rows,
prepareRow,
} = useTable({ cols, data });
return (
<table {...getTableProps()}>
<thead>
{
headerGroups.map(headerGroup => (
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(col => (
<th {...col.getHeaderProps()}>{col.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>
);
};
export default Table;
我在这里跟随 react-table 快速入门指南:https ://github.com/tannerlinsley/react-table/blob/master/docs/quickstart.md
谁能看到我做错了什么?谢谢。