我正在尝试学习react table和react redux,但我无法搜索引用它们一起使用的东西,有人能提供一个我可以引用的例子吗?TIA-
到目前为止,这是我的组件,它没有给我错误,并且可以很好地处理redux状态,但不会在表上呈现数据。
function ResidentTable({ history }) {
const dispatch = useDispatch();
const userLogin = useSelector(state => state.userLogin);
const { userInfo } = userLogin;
const residentList = useSelector(state => state.residentList);
const { loading, error, residents } = residentList;
useEffect(() => {
if (!userInfo || !userInfo.isAdmin) {
history.push('/login');
} else {
dispatch(listResidents());
}
}, [dispatch, history]);
const columns = useMemo(() => RESIDENT_COLUMNS, []);
const data = useMemo(() => residents, []);
const tableInstance = useTable(
{ columns, data },
useFilters,
useGlobalFilter,
useSortBy,
usePagination
);
const {
getTableProps,
getTableBodyProps,
headerGroups,
page,
nextPage,
previousPage,
canNextPage,
canPreviousPage,
prepareRow,
} = tableInstance;
return (
<Box p="2rem 8rem">
<ModalResident />
<Table
size="lg"
variant="striped"
colorScheme="blackAlpha"
{...getTableProps()}
>
<TableCaption placement="top">
<Heading>Metroville Residents List</Heading>
</TableCaption>
<Thead>
{headerGroups.map(headerGroup => (
<Tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map(column => (
<Th
fontSize="1.2rem"
fontFamily="Raleway"
{...column.getHeaderProps(column.getSortByToggleProps())}
>
{column.render('Header')}
<Text as="span">
{column.isSorted ? (
column.isSortedDesc ? (
<ChevronDownIcon />
) : (
<ChevronUpIcon />
)
) : (
''
)}
</Text>
<Box onClick={e => e.stopPropagation()}>
{column.canFilter ? column.render('Filter') : null}
</Box>
</Th>
))}
</Tr>
))}
</Thead>
<Tbody {...getTableBodyProps()}>
{page.map(row => {
prepareRow(row);
return (
<Tr {...row.getRowProps()}>
{row.cells.map(cell => {
return (
<Td
fontSize="1 rem"
fontFamily="Raleway"
{...cell.getCellProps()}
>
{cell.render('Cell')}
</Td>
);
})}
</Tr>
);
})}
</Tbody>
</Table>
<Flex justify="space-between" my="1rem">
<Button disabled={!canPreviousPage} onClick={() => previousPage()}>
<ArrowBackIcon />
Prev
</Button>
<Button disabled={!canNextPage} onClick={() => nextPage()}>
Next
<ArrowForwardIcon />
</Button>
</Flex>
</Box>
);
}
经过实验和之后的许多错误,我重构了代码,使其更加统一和可读,并使其发挥了作用。我将react表组件与另一个分离,这样我就可以在其他表中重用它,并且只添加了加载,这样它将等待redux状态加载,然后将其变为空或出错。
function ResidentTable({ history }) {
const dispatch = useDispatch();
const residentList = useSelector(state => state.residentList);
const { loading, error, residents } = residentList;
const userLogin = useSelector(state => state.userLogin);
const { userInfo } = userLogin;
useEffect(() => {
if (!userInfo || !userInfo.isAdmin) {
history.push('/login');
} else {
dispatch(listResidents());
}
}, [dispatch, history, userInfo]);
const columns = useMemo(() => RESIDENT_COLUMNS, []);
const data = useMemo(() => residents, [residents]);
return (
<Box p="2rem 8rem">
<ModalResident />
{loading ? (
<Loader />
) : error ? (
<Message status="error">{error}</Message>
) : (
<BaseTable data={data} columns={columns} />
)}
</Box>
);
}