多个useEffect React.useEffect缺少依赖项

时间:2019-09-03 14:11:51

标签: reactjs react-hooks

我有一个Products组件,该组件显示某个类别的产品。 从路由参数中获取CategoryId,然后用户可以对产品进行分页。因此,有两种useEffect,一种是更改categoryId时使用,另一种是更改当前页码时。如果我使用一种具有两个依赖项的效果(categoryId和currentPage),则无法找到将当前页码重置为1的方法。(当用户位于类别1并转到2页时,我想重置页码当类别更改时

我创建了以下沙箱: https://codesandbox.io/s/beautiful-shaw-23hqn

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;

2 个答案:

答案 0 :(得分:3)

您有两个效果:

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

答案 1 :(得分:1)

我认为您可以像处理页面一样将类别保持在组件的本地状态。然后,您可以检查本地状态是否与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]);

希望您能理解并且答案会有所帮助。