【问题标题】:sort the product by product price from low to high and vice versa in ReactJs在 ReactJs 中按产品价格从低到高对产品进行排序,反之亦然
【发布时间】:2020-12-28 23:44:41
【问题描述】:

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

一开始,当没有实现商品排序功能时,商品列表还是和以前一样显示。实现排序功能后,商品会从低到高排列,反之亦然

这是我的组组件,其中包含排序和过滤功能

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;

这里是productlistpage,我传递参数是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?

我的排序功能对我不起作用,它保持原样

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

【问题讨论】:

    标签: reactjs sorting filter


    【解决方案1】:

    您应该始终对过滤后的产品进行排序,而不是对原始产品进行排序。在用于排序和过滤的常用函数中,只需检查是否必须过滤某些内容并首先执行所有过滤,然后再进行排序。我假设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。

    【讨论】:

    • 我已经更新了我的问题,请您在产品页面再次查看
    • 非常感谢,但正如您的评论,它对我不起作用
    • 按价格升序和降序排序
    猜你喜欢
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    • 2016-04-01
    • 1970-01-01
    相关资源
    最近更新 更多