gpt4 book ai didi

reactjs - 多个 useEffect React.useEffect 缺少依赖项

转载 作者:行者123 更新时间:2023-12-02 16:52:44 28 4
gpt4 key购买 nike

我有一个产品组件,它显示某个类别的产品。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;

最佳答案

你有两个效果:

1.当 categoryId 改变时,将当前页面设置为 1 :

  React.useEffect(() => {
setCurrentPage(1);
}, [categoryId]);

2.当 categoryIdcurrentPage 改变时获取新数据:

  React.useEffect(() => {
dispatch({
type: "getPaginatedCategoryProducts",
payload: {
categoryId,
pageSize,
pageNumber: currentPage
}
});
}, [currentPage, categoryId, dispatch]);

https://codesandbox.io/s/amazing-cartwright-jdg9j

关于reactjs - 多个 useEffect React.useEffect 缺少依赖项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57773502/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com