Search Filter with React Native on FlatList

前端 未结 10 1209
孤街浪徒
孤街浪徒 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条回答
  •  北海茫月
    2020-12-28 08:54

    I came across this same issue today when trying to implement a filter / search function on the new FlatList component. This is how I managed to solve it:

    By creating another item in the state of the parent component called noData, you can set that to true when there are no results that match your search and then render your FlatList conditionally.

    My implementation is slightly different to yours, but if I had to adjust your code it would look something like this:

    Searchtext function:

    searchText = (e) => {
        let text = e.toLowerCase()
        let trucks = this.state.data
        let filteredName = trucks.filter((item) => {
          return item.name.toLowerCase().match(text)
        })
        if (!text || text === '') {
          this.setState({
            data: initial
          })
        } else if (!Array.isArray(filteredName) && !filteredName.length) {
          // set no data flag to true so as to render flatlist conditionally
          this.setState({
            noData: true
          })
        } else if (Array.isArray(filteredName)) {
          this.setState({
            noData: false,
            data: filteredName
          })
        }
      }
    

    Then pass the noData bool to your TruckList component:

     this.setTruck(truck)} 
    truckScreen={this.truckScreen} data={this.state.data} noData={this.state.noData}/>
    

    Then render your FlatList in the TruckList component only if there are results:

    
    {this.props.noData ? NoData : }         
    
    

    That should then take care of handling user typing errors - as it will re-render the flatlist as soon as there are no results, and will remember the previous search state when you remove the typing error..

    Let me know if that helps!

提交回复
热议问题