【问题标题】:How to make search faster using Debounce Lodash React Native如何使用 Debounce Lodash React Native 加快搜索速度
【发布时间】:2018-08-22 15:30:40
【问题描述】:

如何使用 debounce 加快搜索速度?现在搜索有效,但加载速度很慢。我想它是因为每次按下一个键时它都会搜索。我查看了其他示例,但无法将其应用于我自己的场景。我在我的 Main 组件内的 AutoComplete 组件内的 onChangeText 上调用我的过滤器方法。我如何为我的场景去抖动,因为我需要传入文本即时过滤。

搜索

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

【问题讨论】:

    标签: javascript react-native autocomplete lodash


    【解决方案1】:

    作为开始,我建议开始自动完成搜索所需的最少字符。为什么从 1 个字符开始?通常设置为 2。

    之后你可以用_.debounce包裹filterRooms

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 2021-08-11
      • 2023-01-05
      • 2019-07-26
      • 1970-01-01
      • 2013-10-27
      • 1970-01-01
      相关资源
      最近更新 更多