请在此处查看程序。我有按升序排列的分页数据。第一页全部是升序数据,但下一页不显示升序数据,那么每一页如何分页显示升序数据呢?例如,在第一页上,数据在第二页上显示为 1 2 3,或者其余页面 id 应该像 1 2 3 一样升序,但是当您转到下一页时,它显示 2 3 1 那么如何处理我解决了?
import Pagination from "@mui/material/Pagination";
import { useState } from "react";
export default function App() {
const employees = [
{ id: 2, name: "Bob", country: "Belgium" },
{ id: 3, name: "Carl", country: "Canada" },
{ id: 1, name: "Alice", country: "Austria" },
{ id: 2, name: "Mike", country: "USA" },
{ id: 3, name: "Sam", country: "India" },
{ id: 1, name: "jake", country: "Japan" }
];
const [emp] = useState(employees);
const rowsPerPage = 3;
const [page, setPage] = useState(1);
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
const sortTypes = {
assending: {
class: "assending",
fn: [...emp].sort((a, b) => (a.name > b.name ? 1 : -1))
}
};
const startIndex = (page - 1) * rowsPerPage;
const endIndex = startIndex + rowsPerPage;
const displayedRows = sortTypes.assending.fn.slice(startIndex, endIndex);
return (
<>
<table>
<thead>
<th>ID</th>
<th>Name</th>
<th>Country</th>
</thead>
{displayedRows.map((data, i) => (
<tbody key={i}>
<tr>
<td>{data.id}</td>
<td>{data.name}</td>
<td>{data.country}</td>
</tr>
</tbody>
))}
</table>
<Pagination
count={Math.ceil(emp.length / rowsPerPage)}
color="primary"
variant="outlined"
page={page}
onChange={handleChangePage}
/>
</>
);
}
您似乎想在分页时保持不同页面之间数据的升序。为了实现这一点,您需要确保排序逻辑在所有页面上一致应用。目前,您正在对 sortTypes.assending 对象内的数据进行排序,但它并没有根据当前页面动态使用。
这是解决此问题的代码的更新版本:
import Pagination from "@mui/material/Pagination";
import { useState } from "react";
export default function App() {
const employees = [
{ id: 2, name: "Bob", country: "Belgium" },
{ id: 3, name: "Carl", country: "Canada" },
{ id: 1, name: "Alice", country: "Austria" },
{ id: 2, name: "Mike", country: "USA" },
{ id: 3, name: "Sam", country: "India" },
{ id: 1, name: "Jake", country: "Japan" }
];
const [emp] = useState(employees);
const rowsPerPage = 3;
const [page, setPage] = useState(1);
const handleChangePage = (event, newPage) => {
setPage(newPage);
};
// Sort the data dynamically based on the current page
const sortedData = [...emp].sort((a, b) => (a.name > b.name ? 1 : -1));
const startIndex = (page - 1) * rowsPerPage;
const endIndex = startIndex + rowsPerPage;
const displayedRows = sortedData.slice(startIndex, endIndex);
return (
<>
<table>
<thead>
<th>ID</th>
<th>Name</th>
<th>Country</th>
</thead>
{displayedRows.map((data, i) => (
<tbody key={i}>
<tr>
<td>{data.id}</td>
<td>{data.name}</td>
<td>{data.country}</td>
</tr>
</tbody>
))}
</table>
<Pagination
count={Math.ceil(emp.length / rowsPerPage)}
color="primary"
variant="outlined"
page={page}
onChange={handleChangePage}
/>
</>
);
}
在此修改中,sortedData 数组是在分页逻辑之外创建的,确保无论当前页面如何,数据的排序都是一致的。这样,所有页面都保持升序。