如何使分页再次回到首页?

时间:2019-11-02 02:06:08

标签: reactjs filter pagination

我正在使用过滤器和分页。当我分页并在除第一页之外的任何页面中停止时,然后选择另一个过滤器,它将给我一个空白页,直到我单击此页码为止。当我选择其他过滤器时,我希望分页自动返回首页(默认)。

这是我的分页代码:

import React, { useState } from 'react'

const Pagination = ({productsPerPage, totalPosts, paginate}) => {
const [currentPage, setCurrentPage] = useState(1)

const PageNumbers =[]
const int = Math.ceil(totalPosts / productsPerPage)

    for (let i = 1; i<= int; i++) {
        PageNumbers.push(i) 
    }
    return (
        <nav className="">
            <ul className="pagination">   
            <button
                    className={`${currentPage === 1 ? 'previous-disabled' : ''} prev page-link`}
                    disabled={currentPage === 1}
                    href="!#"
                    onClick={() => { 
                        setCurrentPage(currentPage - 1);
                        paginate(currentPage - 1); 
                    }}
                    > 
                    Previous
          </button>
                        {PageNumbers.map(number => (          
                    (number < 3 || (number > currentPage-2 && number < currentPage+2) || 
                    number > PageNumbers.length - 2 )  ?
                        <li
                            key={number}
                            className={number === currentPage ? "page-item active" : "page-item "}
                        >
                            <a
                                onClick={() => paginate(number)}
                                href="!#"
                                className="page-link"
                                >
                                {number}   
                            </a>
                        </li>
                        :
                        PageNumbers.length>5 && number < 4 ? <a className="page-link">...</a>
                        : 
                        number < PageNumbers.length && number == currentPage+2 ? <a className="page-link">...</a>
                        :null
                    ))}
                <a 
                className={`${currentPage === PageNumbers.length - 1 ? 'paginate-disabled' : ''} next page-link`}
                disabled={currentPage === PageNumbers.length - 1}
                href="!#"
                onClick={() => { 
                    setCurrentPage(currentPage + 1);
                    paginate(currentPage + 1); 
                }}
                > 
                Next
                </a>
            </ul>
        </nav>
    )
}

export default Pagination

0 个答案:

没有答案