在ReactJs中按产品价格从低到高对产品进行排序,反之亦然

时间:2020-09-10 13:04:50

标签: reactjs sorting filter

我正在为产品创建排序功能。但是我在产品页面上的渲染存在一些问题。

首先,当未实现产品分类功能时,产品列表仍会像以前一样显示。实施排序功能后,产品将从低到高列出,反之亦然

这是我的组组件,该位置包含排序和过滤功能

const GroupBar = ({ handleSelectCategory, handleSelectPriceOption }) => {
  return (
    <Row className="group-bar">
      <Group
        title="Product group"
        element={
          <Dropdown
            items={["Milk Tea", "Juice"]}
            onSelect={handleSelectCategory}
          />
        }
      />
      <Group
        title="Sort by price"
        element={<Dropdown
          items={["Low to hight", "Hight to low"]}
          onSelect={handleSelectPriceOption}
        />}
      />
      <Group
        title="Search"
        element={<Search searchTerm="" />}
      />
    </Row>
  );
}

export default GroupBar;

这是主页,其中包含产品列表以及排序和过滤功能,这也是放置连接功能的排序和产品的地方。

const Product = () => {
  const [category, setCategory] = useState("");
  const [priceOption, setpriceOption] = useState("");
  const handleSelectCategory = (item) => {
    setCategory(item);
  };

  const handleSelectPriceOption = (item) => {
    setpriceOption(item);
  };

  return (
    <Container fluid className="p-0">
      <Carousel />
      <Container>
        <GroupBar
          handleSelectCategory={handleSelectCategory}
          handleSelectPriceOption={handleSelectPriceOption}
        />
        <ProductContainer
          category={category}
          priceOption={priceOption}
        />
      </Container>
    </Container>
  );
};

export default Product;

这是productlist页,我通过的参数是priceOption。然后使用useEffect。

const ProductList = ({
  products,
  category,
  priceOption,
  loading,
  fetchProductRequest,
  filterProducts,
}) => {

  useEffect(() => {
    fetchProductRequest();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const [filteredProducts, setFilteredProducts] = useState("");
  const [sortProducts, setsortProducts] = useState("");

  useEffect(() => {
    const result = products
      .filter((it) => !category || it.category === category);
    setFilteredProducts(result);
  }, [category, products]);



     useEffect(() => {
     if (priceOption === "Low to hight") {
       const lth = products.sort((a, b) => a - b);
       setsortProducts(lth);
     }
     if (priceOption === "Hight to low") {
       const htl = products.sort((a, b) => a - b).reverse();
       setsortProducts(htl);
     }
   }, [priceOption, products, sortProducts])

  if (loading) {
    return (
      <Container>
        <Row>
          <Col>
            <Loading />
          </Col>
        </Row>
      </Container>
    );
  }

  return (
    <Container>
      <Row>
        {!!filteredProducts && filteredProducts.length > 0 ? (
          filteredProducts.map((product, index) => {
            return (
              <ProductItem
                key={index}
                image={product.image}
                name={product.name}
                price={product.price}
              />
            );
          })
        ) :
          (
            <h4 className="center-title">Product list is empty!</h4>
          )}
      </Row>
    </Container>
  );
};

export default ProductList;

如何将排序和过滤功能合并到相同的useEffectreturn it in short instead of creating two different useEffect for each function?

我的排序功能不适用于我,它仍然保持原样

还有render what should I do for both functions to show the UI implemented on the product page

1 个答案:

答案 0 :(得分:0)

您应该始终对过滤后的产品而非原始产品进行排序。在用于排序和过滤的通用函数中,只需检查是否必须过滤某些内容并先执行所有过滤,然后再进行排序即可。我假设products数组包含您所有的原始产品。我还假设您用于过滤和排序的逻辑是正确的。

  //always use this state to show contents on the DOM
  const [filteredProducts, setFilteredProducts] = useState(products);

  const sortAndFilter=()=>{
    //always filter and sort from the original array
    const results=products;
    //perform filtering first and then sorting on the filtered array
    if(category) 
    results = products.filter((it) => !category || it.category === category);
    if(priceOption)
    results = results.sort((it) => !priceOption || it.priceOption ==priceOption);

  setFilteredProducts(results);
  }
  useEffect(() => {

   if(category || priceOption) //check if you need to perform filtering/sorting
    sortAndFilter(); 
  else
   setFilteredProducts(products);
  }, [category, priceOption]);

您的渲染方法对我来说似乎还可以,这应该在页面上显示更新的UI。

相关问题