我能够使用 react-table 将我的 API 中的数据加载到表格行中。编译正在运行,我可以在 App 页面上看到数据。但是当我刷新页面时,数据不在这里了。
请看下面我的代码:
import React, {useEffect, useState, useMemo } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { getPosts } from '../../actions/post.actions';
import {useTable, useSortBy, useGlobalFilter, usePagination} from 'react-table'
import {COLUMNS} from './StructureTable'
import { AiOutlineCaretDown, AiOutlineCaretUp } from "react-icons/ai";
import './Table.css'
import GlobalFilter from './GlobalFilter';
const PaginationTable = () => {
// Load database mongoDb
const posts = useSelector((state) => state.postReducer)
const [loadPost, setLoadPost] = useState(true)
const dispatch = useDispatch()
useEffect(() => {
if(loadPost) {
dispatch(getPosts())
setLoadPost(false)
}
}, [loadPost])
const columns = useMemo(() => COLUMNS, [])
const data = useMemo(() => posts, loadPost, [])
const tableInstance = useTable({
columns,
data
},
useGlobalFilter,
useSortBy,
usePagination
)
const {
getTableProps,
getTableBodyProps,
headerGroups,
page,
nextPage,
previousPage,
canNextPage,
canPreviousPage,
pageOptions,
gotoPage,
pageCount,
setPageSize,
prepareRow,
state,
setGlobalFilter,
} = tableInstance
console.log(tableInstance)
const {globalFilter, pageIndex, pageSize} = state
return (
<>
<GlobalFilter filter = {globalFilter} setFilter={setGlobalFilter} />
<br/>
<table {...getTableProps()}>
<thead>
{headerGroups.map(headerGroup =>
<tr {...headerGroup.getHeaderGroupProps()}>
{headerGroup.headers.map((column) =>
<th {...column.getHeaderProps(column.getSortByToggleProps())}>
{column.render('Header')}
<span>
{column.isSorted ? (column.isSortedDesc ? <AiOutlineCaretDown/> : <AiOutlineCaretUp/> ) : ''}
</span>
</th>
)}
</tr>
)}
</thead>
<tbody {...getTableBodyProps()}>
{
page.map((row) => {
prepareRow(row)
return(
<tr {...row.getRowProps()}>
{
row.cells.map(cell => {
return <td {...cell.getCellProps()}>{cell.render('Cell')}</td>
})
}
</tr>
)
})
}
</tbody>
</table>
<div>
<span>
Page{' '}
<strong>
{pageIndex + 1} of {pageOptions.length}
</strong> {' '}
</span>
<span>
| Go to page: {' '}
<input type='number' defaultValue={pageIndex + 1 }
onChange={e => {
const pageNumber = e.target.value ? Number(e.target.value) - 1 : 0
gotoPage(pageNumber)
}}
style={{width:'50px'}}
/>
</span>
<select value={pageSize} onChange={e => setPageSize(Number(e.target.value))}>
{
[10,25,50].map(pageSize => (
<option key={pageSize} value={pageSize}>
Show {pageSize}
</option>
))
}
</select>
<button onClick={() => gotoPage(0)} disabled={!canPreviousPage}>{'<<'}</button>
<button onClick={() => previousPage()} disabled={!canPreviousPage}>Previous</button>
<button onClick={() => nextPage()} disabled={!canNextPage}>Next</button>
<button onClick={() => gotoPage(pageCount - 1)} disabled={!canNextPage}>{'>>'}</button>
</div>
</>
)
}
export default PaginationTable
我错过了什么?