我在 React 中进行了分页,但我没有看到某些内容,因为更改分页的按钮不起作用。 我详细的代码如下:
首先是一个自定义钩子“usePagination”。另一个自定义钩子“useFetch”为我提供了来自 API 的产品列表。现在,如果我将 curretPage 状态的数量更改为两个,它就会起作用,并且 ProductGrid 组件中的列表会刷新并显示接下来的 16 个产品。我在下一个代码的下方展示了 Pagination 和 ProductGrid 组件:
export const usePagination = () => {
const { data } = useFetch();
const productsByPage = 16;
const [currentPage, setCurrentPage] = useState(1);
function refreshPage( number ) {
const indexLastProduct = (number) * productsByPage;
const indexFirstProduct = indexLastProduct - productsByPage;
const list = data.slice(indexFirstProduct, indexLastProduct);
return list;
}
let productList = refreshPage( currentPage );
function changePage(number) {
setCurrentPage(number);
}
return {
productsByPage,
productList,
currentPage,
changePage
};
}
“Pagination”组件来自我调用 usePagination 返回的 productsByPage、productList、currentPage 和“changePage”函数。在两个 CustomFAB 按钮中,我都实现了“changePage”函数,该函数为我提供了 usePagination,并在 onClick 事件中将其设置为要转到的页码:
export const Pagination = ( { isVisible } ) => {
const {
productsByPage,
currentPage,
changePage } = usePagination();
const [ filterVisivility ] = useState( isVisible );
const { data } = useFetch();
return (
<div className="pagination-bar">
<div
className="
store__pagination-container
align-horizontal
d-flex
align-items-center">
<p className="store__counter-pager">
{ productsByPage } of { data.length }
<span>products</span>
</p>
{ filterVisivility && <FilterBar /> }
<ul className="pagination-nav align-horizontal right-align">
<li>
{
!currentPage === 1 &&
<CustomFAB
iconName={ 'chevron_left' }
onClickFab={ ()=> { changePage( 1 ) } }
/>
}
</li>
<li>
<CustomFAB
iconName={ 'chevron_right' }
onClickFab={ ()=> { changePage( 2 ) } }
/>
</li>
</ul>
</div>
<hr />
</div>
)
}
最后,在 ProductGrid 组件中,我将产品列表从 usePagination 钩子分页显示出来,但是在 Pagination 组件和 usePagination 自定义钩子之间的通信中有些东西不起作用:
export const ProductGrid = () => {
const { productList } = usePagination();
const { loading } = useFetch();
const isMobile = useMediaQuery({ query: `(min-width: 760px)` });
return (
<>
{ loading && <SkeletonGrid /> }
{
!isMobile
? <OwlCarousel
className='owl-theme'
dots={ false }
items={ 1 }
margin={ 25 }
nav>
{
productList.map( prod => (
<ProductItem
key={ prod.id }
{ ...prod }
/>
))
}
</OwlCarousel>
:
<div className="row">
{
productList.map( (prod, key) => (
<ProductItem
key={ key }
{ ...prod }
/>
))
}
</div>
}
</>
)
}
请帮忙?。非常感谢。