React挂钩具有不同参数的相同组件Paginator索引

时间:2019-07-14 18:31:55

标签: reactjs react-hooks

我正在编写一个带有反应的产品目录项目,以供学习。 我有一个CategoryTree组件,当选择了叶子类别时,我将该类别的ID发送到CategoryProducts组件。 (如http://localhost:3000/category-products/5d29f637842b1e3b789af3d2

在这种情况下,我单击一个类别,该类别将我带到CategoryProducts组件。

<?php

include 'config.php';

$query = "SELECT d_domain, d_purchase_price, d_selling_price FROM 
domains";
$result = mysqli_query($con, $query);

if (mysqli_num_rows($result) > 0) {
    $delimiter = ",";
    $filename = "data.csv";
    $output = fopen('php://memory', 'w');
    $fields = array('Domain Name', 'Purchase Price', 'Selling Price');
    fputcsv($output, $fields, $delimiter);

    while ($row = mysqli_fetch_assoc($result)) {
        $lineData = array($row['d_domain'], $row['d_purchase_price'],
            $row['d_selling_price']);
        fputcsv($output, $lineData, $delimiter);
    }
    fseek($output, 0);

    header('Content-Type: text/csv; charset=utf-8');
    header('Content-Disposition: attachment; filename= data.csv');

    fpassthru($f);
}

在CategoryProducts页面中,我使用分页,然后导航到第5页。

然后,当我单击其他类别时,如果categoryId更改,则当前页面仍为5,并且我不知道如何将其重置为1。

props.history.push(`/category-products/${SOME_ID}`);

当选择了不同类别时,我希望currentPage为1。

import React, { useState, useEffect } from "react";
import { Row, Pagination } from "antd";
import axios from "axios";
import ProductCard from "./ProductCard";

const CategoryProducts = ({ match }) => {
  const [products, setProducts] = useState([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const PAGE_SIZE = 5;

  useEffect(() => {
    const fetchProduct = async id => {
      const result = await axios.get(
        `http://localhost:3001/api/v1/product/categoryProducts/${id}?pageIndex=${currentPage}&pageSize=${PAGE_SIZE}`
      );
      setProducts(result.data.products);
      setTotal(result.data.productsCount[0].total);
    };

    fetchProduct(match.params.id);
  }, [match.params.id, currentPage]);

  const productCards = () => {
    return products.map(p => <ProductCard product={p} key={p._id} />);
  };

  const showTotal = total => {
    return `Total ${total} items`;
  };

  const onPageChange = page => {
    setCurrentPage(page);
  };

  return (
    <div style={{ padding: "10px" }}>
      <Row gutter={4}>{productCards()}</Row>
      <Pagination
        current={currentPage}
        pageSize={PAGE_SIZE}
        size="small"
        total={total}
        showTotal={showTotal}
        onChange={onPageChange}
      />
      Current Page: {currentPage}
    </div>
  );
};

export default CategoryProducts;

更新

我可以通过使用两个useEffect挂钩解决问题, 如果来自match.params.id依赖项,则将当前页面设置为1:

const [currentPage, setCurrentPage] = useState(1);

唯一的问题是以下警告:

./ src / components / product / CategoryProducts.jsx   第23行:React Hook useEffect缺少依赖项:“ currentPage”和“ fetchProducts”。包括它们或删除依赖项数组react-hooks / exhaustive-deps   第27行:React Hook useEffect缺少依赖项:“ fetchProducts”和“ match.params.id”。要么包含它们,要么删除依赖项数组react-hooks / exhaustive-deps

2 个答案:

答案 0 :(得分:0)

在构建此示例时,我遇到了您遇到的相同错误。我通过将useEffect挂钩条件设置为在currentPage上更新来修复它。显然,您的实现需要与我使用的这个伪造的数据源稍有不同,但这可能就是问题所在。

fetchMySuperContent

答案 1 :(得分:0)

我可以通过如下分离useEffects依赖项来将页码重置为1:

import React, { useState, useEffect, useCallback } from "react";
import { Row, Pagination } from "antd";
import axios from "axios";
import ProductCard from "./ProductCard";

const CategoryProducts = ({ match }) => {
  const [products, setProducts] = useState([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const PAGE_SIZE = 5;

  const fetchProducts = useCallback(async (id, currentPage) => {
    const result = await axios.get(
      `http://localhost:3001/api/v1/product/categoryProducts/${id}?pageIndex=${currentPage}&pageSize=${PAGE_SIZE}`
    );
    setProducts(result.data.products);
    setTotal(result.data.productsCount[0].total);
  }, []);

  useEffect(() => {
    setCurrentPage(1);
    setTotal(0);
    fetchProducts(match.params.id, currentPage);
  }, [match.params.id]);

  useEffect(() => {
    fetchProducts(match.params.id, currentPage);
  }, [currentPage]);

  const productCards = () => {
    return products.map(p => <ProductCard product={p} key={p._id} />);
  };

  const showTotal = total => {
    return `Total ${total} items`;
  };

  const onPageChange = page => {
    setCurrentPage(page);
  };

  return (
    <div style={{ padding: "10px" }}>
      <Row gutter={4}>{productCards()}</Row>
      <Pagination
        current={currentPage}
        pageSize={PAGE_SIZE}
        size="small"
        total={total}
        showTotal={showTotal}
        onChange={onPageChange}
      />
      Current Page: {currentPage}
    </div>
  );
};

export default CategoryProducts;