Search Filter with React Native on FlatList

前端 未结 10 1215
孤街浪徒
孤街浪徒 2020-12-28 08:33

I am trying to search through a flatlist based on a search bar text. The problem I am running into is that when the user mistypes...say they wanted to type \"burger\" but ty

10条回答
  •  萌比男神i
    2020-12-28 08:46

    Update: This blog can help you better understand the searching in a FlatList.

    FYI: If you have huge online data then you can also use algolia.

    I adjusted the above code for me in order to make it work properly. The reason is that when user removes the last wrong character, code search this new string from a previous search list (state) which does not contain all objects, although it had to search from a full list available. So, I have two list now. One contains full list of objects and second contains only rendered list of objects which is changing upon search.

    handleSearchInput(e){
        let text = e.toLowerCase()
        let fullList = this.state.fullListData;
        let filteredList = fullList.filter((item) => { // search from a full list, and not from a previous search results list
          if(item.guest.fullname.toLowerCase().match(text))
            return item;
        })
        if (!text || text === '') {
          this.setState({
            renderedListData: fullList,
            noData:false,
          })
        } else if (!filteredList.length) {
         // set no data flag to true so as to render flatlist conditionally
           this.setState({
             noData: true
           })
        }
        else if (Array.isArray(filteredList)) {
          this.setState({
            noData: false,
            renderedListData: filteredList
          })
        }
      }
    

提交回复
热议问题