我有一个Products组件,它显示一个类别的产品。CategoryId是从路由参数中获取的,然后用户可以对产品进行分页。因此有两个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;发布于 2019-09-03 22:23:40
您有两种效果:
1.当categoryId发生变化时,将当前页面设置为1:
React.useEffect(() => {
setCurrentPage(1);
}, [categoryId]);2.当categoryId或currentPage发生变化时,获取新数据:
React.useEffect(() => {
dispatch({
type: "getPaginatedCategoryProducts",
payload: {
categoryId,
pageSize,
pageNumber: currentPage
}
});
}, [currentPage, categoryId, dispatch]);发布于 2019-09-03 22:26:19
我认为你可以将类别保持在组件的本地状态,就像你对页面所做的那样。然后,您可以检查本地状态是否与Redux状态匹配。如果没有,您可以重置页码并设置新类别,或者仅在需要时更改页码。另一个useEffect可能不会处理类别更改,因为它不是本地状态更改,并且useEffect仅在本地状态更改时触发。这里有一个可能会有帮助的例子
React.useEffect(() => {
if(categoryId!==currentCategory){
dispatch({
type: "getPaginatedCategoryProducts",
payload: {
categoryId,
pageSize,
pageNumber: 1
}
});
}
else{
dispatch({
type: "getPaginatedCategoryProducts",
payload: {
categoryId,
pageSize,
pageNumber: currentPage
}
});
}
}, [categoryId,currentPage]);我希望你能理解,答案是有帮助的。
https://stackoverflow.com/questions/57773502
复制相似问题