Multiple filters in React

后端 未结 2 512
北恋
北恋 2020-12-22 04:41

I am building a project that displays some data from api and now I need to filter it.

I\'ve done the category filter and now I have to do a price range filter so bot

相关标签:
2条回答
  • 2020-12-22 05:42

    i have same problem with marge filters i have two filters and each one works fine but together not works only first work my code is

    const [search, setSearch] = useState('');
    const [select, setSelect] = useState('All');
    
    
    const updateSearch = (e) => {
        setSearch(e.target.value);
        //console.log(search);
      }
    
    const updateSelect = (e) => {
        setSelect(e.target.value);
        //console.log(select);
    }
    
    const searchCountry = zemlje.filter((zemlja) => {
        if (zemlja.name.toLowerCase().search(new RegExp(`^${search}`)) === 0) return true;
    });
    
    const selectCountry = zemlje.filter((zemlja) => {
        if (select ==='All') return true;
        if (zemlja.region === select) return true;
    });
    

    i want filter this base on search input and select drop menu

            <div className="atlas">
                {searchCountry.map(zemlja => (
    
                    <JednaZemlja 
                    key={zemlja.alpha3Code}
                    name={zemlja.name}
                    flag={zemlja.flag}
                    population={zemlja.population}
                    region={zemlja.region}
                    capital={zemlja.capital}
                    />
    
                ))}
    
    0 讨论(0)
  • 2020-12-22 05:47

    You should write a new filter function which merges these filters together. And use it like this:

    filterBender = data => {
        const {bender, person, nation} = this.state;
        if(bender && data.bender !== bender) return false;
        if(person && data.person !== person) return false;
        if(nation && data.nation !== nation) return false;
        ...
        return true;
    }
    
    const visibelBenders = filterData.filter(filterBender);
    

    This way, you will only filter your data once and every bender gets evaluated for each constraint once. At the end, only the bender which returns true for all the different ifs will be inserted into the visibelBenders array, which you could render. Additionally, you could wrap this into a memorization function to only execute it, if one of the filters changed.

    To display all benders, if no filter is set you could wrap the filter into a new function to check if filtering is enabled.

    const getBenders = () => {
        const { bender, person, nation} = this.state;
        if( person || bender || nation ){
             return this.filterData.filter(filterBender);
        } else {
           return this.filterData;
        }
    }
    const benders = getBenders();
    
    0 讨论(0)
提交回复
热议问题