React native搜索框实时模糊搜索

本文介绍了一种优化实时搜索用户体验的方法,通过使用定时器减少不必要的服务器请求,提高搜索效率。具体实现包括利用TextInput组件监听用户输入行为,并在用户暂停输入1秒后发送请求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

搜索框样式

<View style={{ paddingRight: 15, paddingLeft: 15, marginTop: 10 }}>
            <View style={{ height: 40, backgroundColor: "#fff", borderRadius: 10, paddingLeft: 25, flexDirection: 'row', alignItems: 'center' }} >
              <Image source={require('../images/search/magnifier.png')} style={{ width: 15, height: 15 }}></Image>
              <TextInput underlineColorAndroid="transparent" placeholder="商户简称/全称" style={{ marginLeft: 10, width: 150 }}
                onChangeText={this._onChangeText.bind(this)}
                value={this.state.inputValue}
                ref="keyWordInput"
                onSubmitEditing={() => { this.refs.keyWordInput.blur() }}>
              </TextInput>
              <TouchableOpacity onPress={() => { dismissKeyboard() }} style={styles.searchView}>
                <Text style={{ color: '#0391ff', fontSize: 14 }}>搜索</Text>
              </TouchableOpacity>
            </View>
          </View>

思路:关于实现实时搜索,在搜索关键字的过程中需要不停地向服务器发起请求,这样才能根据输入的内容呈现不同的搜索结果。可是如果不停地fetch请求,因为fetch请求是异步进行,在输入第一个字的时候开始fetch请求,此时又输入的二个字,而第一个fetch请求还没结束,第二个fetch请求又来,这样会造成服务器崩溃,也不会有良好的用户体验。所以在做模糊搜索的时候,要尽量减少服务器请求,尽可能地根据用户停顿时间一步到位地知道用户想搜索什么,从而给出结果。

通过在textInput的监听函数中进行

 onChangeText={this._onChangeText.bind(this)}
 _onChangeText(text) {
    if (text) {
      this.setState({ inputValue: text })  //实时变化值
      clearTimeout(this.settimeId);       //如搜索的内容变化在1秒之中,可以清除变化前的fetch请求,继而减少fetch请求。但不能中断fetch请求
      this.settimeId = setTimeout(() => {
        var jsonData = {
          "sessionId": global.appInfo.sessionId,
          "merchName": text,
        };
        console.log(jsonData)
        Utils.fetchData('nsposm/B1404/queryMerchList', jsonData, this.SearchCallback);
      }, 1000);                                      //让每次要进行fetch请求时先延迟1秒在进行
      console.log("sheng chen id:" + this.settimeId);

    } else {
      this.setState({inputValue: '' })
    }

}



评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值