【发布时间】: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;
如何将排序和过滤功能组合到同一个 useEffect 和 return 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
【问题讨论】: