answer -我已经更新了下面的代码以显示工作示例。
我目前正在用过滤器系统在React中构建一个投资组合。例如,用户将转到作品集页面并选择他们想要查看项目的过滤器(网页设计、开发等)。
我已经创建了一个名为updatedProjects的新数组,它应该包含从ProjectData中过滤出来的项目。我在下面提供了一个例子,我要求updatedProjects包含任何带有"品牌标识"标签的项目。或"网页设计">
ProjectData.tsx
const ProjectData = [
{
title: "Project 1",
tags: [
{ title: "Web Development", value: "web-development" },
],
},
{
title: "Project 2",
tags: [
{ title: "Brand Identity", value: "brand-identity" },
{ title: "Brand Messaging", value: "brand-messaging" },
],
},
{
title: "Project 3",
tags: [
{ title: "Brand Identity", value: "brand-identity" },
{ title: "Brand Guidelines", value: "brand-guidelines" },
{ title: "Brand Messaging", value: "brand-messaging" },
{ title: "Web Design", value: "web-design" },
],
},
];
Projects.tsx
const filterProjects = (title) => {
// if filter is not already in array, add it. Else, remove it.
let updatedFilters = [];
if (!selectedFilters.includes(title)) {
updatedFilters = [...selectedFilters, title];
}
else {
const updatedTags = selectedFilters.filter((el) => el !== title);
updatedFilters = updatedTags;
}
setSelectedFilters(updatedFilters);
let updatedProjects = [];
// Here I need to filter ProjectData using the selectedFilters state array.
// This currently just filters by the most recent filter 'title', and not by
// ALL titles in the selectedFilters array.
updatedProjects = ProjectData.filter((project) =>
project.tags.some((tag) => updatedFilters.includes(tag.title))
);
setFilteredProjects(updatedProjects);
};
我看了一下你的旧代码。您可以按照下面的操作来实现所需的结果。
const filterProjects = (title) => {
// if filter is not already in array, add it. Else, remove it.
let updatedFilters = [];
if (!selectedFilters.includes(title)) {
updatedFilters = [...selectedFilters, title];
}
else {
const updatedTags = selectedFilters.filter((el) => el !== title);
updatedFilters = updatedTags;
}
setSelectedFilters(updatedFilters);
let updatedProjects = [];
// Here I need to filter ProjectData using the selectedFilters state array.
// This currently just filters by the most recent filter 'title', and not by
// ALL titles in the selectedFilters array.
updatedProjects = ProjectData.filter((project) =>
project.tags.some((tag) => updatedFilters.includes(tag.title))
);
setFilteredProjects(updatedProjects);
};