简体   繁体   English

如何使用Debounce Lodash React Native加快搜索速度

[英]How to make search faster using Debounce Lodash React Native

How can I make my search faster using debounce? 如何使用去抖功能使搜索更快? Right now the search works but its loading pretty slow. 目前,搜索有效,但加载速度很慢。 I imagine its because its searching every time a key is pressed. 我想像是因为每次按下一个键就进行搜索。 I looked at the other examples and I am having trouble applying it to my own scenario. 我查看了其他示例,但在将其应用于自己的方案时遇到了麻烦。 I call my filter method on onChangeText inside the AutoComplete component which is inside my Main component. 我在主组件内的AutoComplete组件内的onChangeText上调用过滤方法。 How can I debounce this for my scenario, as I need to pass in the text im filtering. 由于需要传递文本im过滤,因此如何针对我的情况对此进行反跳处理。

SEARCH 搜索

  filterRooms = (text) => {
    const { rooms } = this.state;
    if(text && text.length > 0) {
      newSearch = rooms.filter(room => room.toLowerCase().includes(text.toLowerCase()))
  }

  // set the state
  this.setState({ rooms: newSearch, query: text, hideResults: false });

  }
}

AUTOCOMPLETE AUTOCOMPLETE

<Autocomplete
          data={this.state.rooms}
          defaultValue={query}
          hideResults={ hideResults }
          onBlur={ () => this.setState({ hideResults: true }) }
          onFocus={ () => this.setState({ hideResults: false }) }
          onChangeText={ text => this.filterRooms(text) }
          renderItem={item => (
            <TouchableOpacity onPress={() => this.setState({ query: item })}>
              <Text>{item}</Text>
            </TouchableOpacity>
          )}
        />

As a start I would suggest to have a min characters required to begin the auto complete searches. 首先,我建议使用最小字符来开始自动完成搜索。 Why start at 1 char? 为什么从1个字符开始? Usually this is set to 2. 通常将此设置为2。

After that you can just wrap filterRooms with _.debounce : 之后,你可以只是包装filterRooms_.debounce

constructor(props) {
    super(props);
    this.filterRooms = _.debounce(this.filterRooms, 1000);
}
filterRooms = (text) => {
    const { rooms } = this.state;
    if(text && text.length > 0) {
        newSearch = rooms.filter(room => room.toLowerCase().includes(text.toLowerCase()))
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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