我有一个列出一些产品的列表,这些产品分为几类。
我正在尝试通过复选框对这些类别应用过滤器。当用户选中该复选框时,必须使用所选类别更新列表。
我想知道如何根据复选框选择呈现产品列表吗?
我将代码放入codesandbox中,因为其中包含很多文件。
例如,在这里我只想渲染Chypre
和Floriental
类别的产品。
我在这里显示我的产品列表:
import React, { useState, useMemo, useEffect } from "react";
import { useSelector } from "react-redux";
import CardItem from "../CardItem";
import Pagination from "../Pagination";
import Search from "../Search";
import { useStyles } from "./styles";
const Card = (props) => {
const { activeFilter } = props;
const classes = useStyles();
const data = useSelector((state) => state.perfume.collections);
const [searchPerfume, setSearchPerfume] = useState("");
const [currentPage, setCurrentPage] = useState(1);
const [perfumesPerPage, setPerfumesPerPage] = useState(3);
console.log("activeFilter: ", activeFilter);
const orderList = data
.map((item) => ({
...item,
totalSize: item.sizes.reduce((sum, cur) => sum + cur.price, 0)
}))
.sort((a, b) => a.totalSize - b.totalSize);
const filteredPerfumes = useMemo(() => {
return orderList.filter((perfume) =>
perfume.name.toLowerCase().includes(searchPerfume.toLowerCase())
);
}, [orderList, searchPerfume]);
const currentPerfumes = filteredPerfumes.slice(
(currentPage - 1) * perfumesPerPage,
currentPage * perfumesPerPage
);
const pages = Math.ceil(filteredPerfumes.length / perfumesPerPage);
useEffect(() => {
if (currentPage > pages) {
setCurrentPage(1);
}
}, [currentPage, pages]);
const pageNumbers = Array(pages)
.fill(null)
.map((val, index) => index + 1);
const handleClick = (page) => {
setCurrentPage(page);
};
return (
<div>
<Search
data-testid="input-filter-id"
setSearchPerfume={setSearchPerfume}
/>
{currentPerfumes
.filter((perfume) => {
return (
perfume.name.toLowerCase().indexOf(searchPerfume.toLowerCase()) >= 0
);
})
.map((item) => (
<CardItem key={item.id} item={item} />
))}
<Pagination
pageNumbers={pageNumbers}
handleClick={handleClick}
currentPage={currentPage}
/>
</div>
);
};
export default Card;
谢谢。
答案 0 :(得分:3)
尝试那个
const filteredPerfumes = useMemo(() => {
const filtered = orderList.filter((perfume) =>
perfume.name.toLowerCase().includes(searchPerfume.toLowerCase())
);
if (activeFilter.length > 0) {
return filtered.filter((item) => item.categories.some((a) =>
activeFilter.some((v) => v.text === a)
));
}
return filtered;
}, [orderList, searchPerfume]);