javascript - 如何用分页做点击项目?
问题描述
使用 react.js。捕捉难以理解的错误。我的没有分页的组件运行良好 - 向您显示所有项目,您可以通过单击查看项目。分页也可以正常工作,但我无法单击项目列表中的项目。实际上我可以点击,但只显示首页项目。如果您从 2-nd(3,4...n) 页面单击项目,您将获得来自 1-st 页面的项目。
export function ListOfItems() {
const [currentPage, setCurrentPage] = useState(1);
const [postsPerPage] = useState(10);
const users = useSelector(state => state);
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
const currentPosts = users.slice(indexOfFirstPost, indexOfLastPost);
const paginate = pageNumber => setCurrentPage(pageNumber);
let items = currentPosts.map(function (value, index) {
return (
<form key={index}>
<div className="input-group">
<div className="input-group-prepend">
<Link className="input-group-text" to={`${url}/${index}`}>
{value.name}
</Link>
</div>
</div>
</form>
)
});
return (
<div>
<div>{items}</div>
<Pagination postsPerPage={postsPerPage} totalUsers={users.length} paginate={paginate}/>
</div>
)
}
解决方案
最近我建立了像你这样的东西。有一种更干净的方法可以做到这一点。我建议您在自定义挂钩中分离您的逻辑。例如,您可以创建自定义钩子:
export const usePagination = (posts, defaultPage = 1, amountPerPage = 10) => {
const [currentPage, setCurrentPage] = useState(defaultPage);
const [postsPerPage] = useState(amountPerPage);
const indexOfLastPost = currentPage * postsPerPage;
const indexOfFirstPost = indexOfLastPost - postsPerPage;
let currentPosts = [];
let amountOfPages = 0;
if (Array.isArray(posts)) {
currentPosts = posts.slice(indexOfFirstPost, indexOfLastPost);
amountOfPages = Math.ceil(posts.length / postsPerPage);
}
return {
setCurrentPage,
amountOfPages,
currentPosts,
};
};
并在您需要的任何组件中使用它。例如:
const { setCurrentPage, currentPosts, amountOfPages } = usePagination(yourArrayOfData);
例如,您可以这样使用它(我使用的是 Material UI Pagination 组件):
<Pagination
count={amountOfPages}
onChange={(event, page) => setCurrentPage(page)}
/>
并使用 currentPosts 实际显示您的数据。我知道,这不是你问题的直接答案,但最近我写了一些像你一样的东西,而且效果很好。所以我希望我的解决方案能帮到你。
推荐阅读
- javascript - jQuery v3.0 不再支持 unbind 了,真的吗?
- c# - 如何检查游戏对象是否处于活动状态
- c# - 脚本,附加到 2 个场景,不起作用
- javascript - 即使焦点集中,使用 Enter/Space 键单击元素也不起作用(可访问性)
- rdf - owlready2 rdfs:subClassOf 推理不起作用
- c - 在while循环中多次调用函数
- mysql - 如何按 id 删除 mySQL JSON 列元素,而不是按索引 num
- html - 如何将网格与引导程序一起用于表单(v3)?
- c++ - C++ 部分运行程序,直到我切换到 DOS shell
- python - 将带有光标的小部件移动到另一个布局