【发布时间】:2020-01-06 11:14:28
【问题描述】:
我有一个 Products 组件,它显示一个类别的产品。 CategoryId 取自路由参数,然后用户可以对产品进行分页。所以有 2 个 useEffect 一个是 categoryId 改变的时候,一个是当前页码改变的时候。如果我使用一个具有两个依赖项(categoryId 和 currentPage)的效果,我找不到将当前页码重置为 1 的方法。(当用户处于类别 1 并转到 2 页时,我想重置页码当类别发生变化时)
import React from "react";
import {
useProductState,
useProductDispatch
} from "../contexts/product.context";
const Products = props => {
const categoryId = +props.match.params.id;
const { categoryProducts, totalCount } = useProductState();
const [currentPage, setCurrentPage] = React.useState(1);
const dispatch = useProductDispatch();
const pageSize = 2;
const pageCount = Math.ceil(+totalCount / pageSize);
React.useEffect(() => {
setCurrentPage(1);
dispatch({
type: "getPaginatedCategoryProducts",
payload: {
categoryId,
pageSize,
pageNumber: currentPage
}
});
}, [categoryId]);
React.useEffect(() => {
dispatch({
type: "getPaginatedCategoryProducts",
payload: {
categoryId,
pageSize,
pageNumber: currentPage
}
});
}, [currentPage]);
const changePage = page => {
setCurrentPage(page);
};
return (
<div>
<h1>Category {categoryId}</h1>
{categoryProducts &&
categoryProducts.map(p => <div key={p.id}>{p.name}</div>)}
{pageCount > 0 &&
Array.from({ length: pageCount }).map((p, index) => {
return (
<button key={index + 1} onClick={() => changePage(index + 1)}>
{index + 1}
</button>
);
})}
<br />
currentPage: {currentPage}
</div>
);
};
export default Products;
【问题讨论】:
标签: reactjs react-hooks