首页 > 解决方案 > 如何用分页做点击项目?

问题描述

使用 react.js。捕捉难以理解的错误。我的没有分页的组件运行良好 - 向您显示所有项目,您可以通过单击查看项目。分页也可以正常工作,但我无法单击项目列表中的项目。实际上我可以点击,但只显示首页项目。如果您从 2-nd(3,4...n) 页面单击项目,您将获得来自 1-st 页面的项目。

用我的代码打开 CodePen

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>
    )
}

标签: javascriptreactjspagination

解决方案


最近我建立了像你这样的东西。有一种更干净的方法可以做到这一点。我建议您在自定义挂钩中分离您的逻辑。例如,您可以创建自定义钩子:

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 实际显示您的数据。我知道,这不是你问题的直接答案,但最近我写了一些像你一样的东西,而且效果很好。所以我希望我的解决方案能帮到你。


推荐阅读