在FlatList上使用React Native搜索过滤器 [英] Search Filter with React Native on FlatList

查看:86
本文介绍了在FlatList上使用React Native搜索过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据搜索栏文本搜索平面列表。我遇到的问题是,当用户输入错误时...说他们想输入汉堡但是错误地键入burget然后它不会返回任何内容。当用户删除t时,它应该重新渲染平面列表,最后一个文本与burge部分匹配。

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 typed "burget" by mistake then it returns nothing as it should. When the user deletes the "t" then it should re-render the flatlist again with the last text matching the "burge" part.

注意:使用react-native-元素搜索栏,它允许我只用e或事件调用文本。

note: using react-native-elements search bar which allows me to call the text with just e or event.

到目前为止我在Main.js文件中有什么:

What I have so far in the Main.js file:

searchText = (e) => {
    let text = e.toLowerCase();
    let trucks = this.state.data;

    // search by food truck name
    let filteredName = trucks.filter((truck) => {
      return truck.name.toLowerCase().match(text); 
    });

    // if no match and text is empty
    if(!text || text === '') {
      console.log('change state');
        this.setState({
          data: initial
        });
      }
    // if no name matches to text output
    else if(!Array.isArray(filteredName) && !filteredName.length) {
      console.log("not name");
      this.setState({
        data: [],
      });
    }
    // if name matches then display
    else if(Array.isArray(filteredName)) {
      console.log('Name');
      this.setState({
        data: filteredName,
      });
    }
   };

<View style={styles.container}>
  <SearchBar
    round
    lightTheme
    containerStyle={styles.search}
    ref="search"
    textInputRef="searchText"
    onChangeText={this.searchText.bind(this)}
    placeholder='Search by Truck Name...'
   />
   <TruckList getTruck={(truck) => this.setTruck(truck)} truckScreen={this.truckScreen} data={this.state.data}/>
</View>

然后是TruckList.JS:

then the TruckList.JS:

export default class TruckList extends Component {
    // rendering truck screen
    renderTruckScreen = (item) => {
        this.props.truckScreen();
        this.props.getTruck(item);
    }

    render() {
        return(
            <List style={styles.list}>
                <FlatList
                    data={this.props.data}
                    renderItem={({ item }) => (
                        <ListItem
                            roundAvatar
                            avatar={{uri: item.pic1}}
                            avatarStyle={styles.avatar}
                            title={item.name}
                            titleStyle={styles.title}
                            subtitle={
                                <View style={styles.subtitleView}>
                                    <Text style={styles.subtitleFood}>{item.food}</Text>
                                    <View style={styles.subtitleInfo}>
                                        <Icon 
                                            name="favorite"
                                            size={20}
                                            color={"#f44336"}
                                            style={styles.subtitleFavorite}
                                        />
                                        <Text style={styles.subtitleFavoriteText}>{item.favorited} favorited</Text>
                                    </View>
                                </View>
                            }
                            onPress={() => this.renderTruckScreen(item)}
                        />
                    )}
                    keyExtractor={(item) => item.uid}
                    ListFooterComponent={this.footer}
                />
            </List>
        )
      }
    }

我尝试过其他一些无济于事的方式。我见过的唯一可用于React Native的解决方案是ListView,它会及时折旧。所以我想尝试使用新的FlatList组件。

I have tried a few other ways to no avail. Also the only solutions I have seen working for React Native are with ListView which will be depreciated in time. So I am trying to do this with the new FlatList Component.

感谢您的帮助!

推荐答案

当我尝试在新的FlatList组件上实现过滤器/搜索功能时,我今天遇到了同样的问题。这就是我设法解决它的方法:

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:

通过创建名为noData的父组件状态中的另一个项目,可以在没有结果的情况下将其设置为true匹配你的搜索,然后有条件地渲染你的FlatList。

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功能:

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
      })
    }
  }

然后将noData bool传递给您的TruckList组件:

Then pass the noData bool to your TruckList component:

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

只有在有结果的情况下才会在TruckList组件中渲染FlatList:

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

<List style={styles.list}>
{this.props.noData ? <Text>NoData</Text> : <FlatList {...} />}         
</List>

然后应该处理用户输入错误 - 因为它会尽快重新呈现平面列表由于没有结果,并且在您删除输入错误时会记住之前的搜索状态。

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!

这篇关于在FlatList上使用React Native搜索过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆