简体   繁体   中英

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 .

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 data by category:

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

var result = data[category_key];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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