简体   繁体   English

如何使用反应在列表中应用过滤器

[英]how to apply filter in list using react

I make a demo application.我做了一个演示应用程序。 In which I have few categories example like Watches, Jeans, etc其中我有几个类别的例子,比如手表、牛仔裤等

I want to apply filter when I click on any category.我想在单击任何类别时应用过滤器。 In other words I want to show products that of selected category.换句话说,我想展示所选类别的产品。

here is my code这是我的 代码

Steps脚步

  1. Initially all items are displayed最初显示所有项目
  2. when I apply filter Sports Shoes it shows only two item .当我应用过滤器运动鞋时,它只显示两个项目
  3. but my issue is I am iteration in whole list every time.我的问题是我每次都在整个列表中迭代 Is there any better way?有没有更好的办法?

     useEffect(() => { let fArr = state.filter(i => filterArray.indexOf(i.category);= -1); setProductState(fArr), }; [filterArray]);

any filter selected选择的任何过滤器

const onItemClickHandler = item => {
    setFilterArray([...filterArray, item]);
};

bug or any better approach错误或任何更好的方法

whenever I am applying any filter I am iteration whole list again and again any better approach.每当我应用任何过滤器时,我都会一次又一次地迭代整个列表任何更好的方法。 Actually currently I have only 100 products.let take it it is 100,000 products I will iterate again and again in 100,000 .实际上目前我只有100 个产品。假设它是100,000 个产品,我将在100,000 个中一次又一次地迭代。

any better approach?有什么更好的方法吗?

If you have more than thousands data, it's better to map all your data by group, then you only need to use key to retrieve them.如果你有几千条以上的数据,最好将你所有的数据分组到map,然后你只需要使用key来检索它们。

Map data by category: Map 数据分类:

var data = filterArray.reduce((x,v) => {
    (x[v.category] = x[v.category] || []).push(v)
    return x
}, {});

If you select the category, you can get the data faster如果你select这个类别,可以更快的获取数据

var result = data[category_key];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM