关于React native onEndReached使用心得

任务需求:做一个搜索框,根据用户输入内容不断进行模糊搜索,使搜索结果可以分页,下拉触发更多数据。搜索结果用了一个ListView控件,并使用了onEndReached函数。

如下所示:

<ListView
                    keyboardShouldPersistTaps='always'
                    dataSource={ds.cloneWithRows(this.state.dataSource)}
                    renderRow={this._renderRow.bind(this)}
                    enableEmptySections={true}
                    onEndReachedThreshold={100}
                    onEndReached={()=>this.loadingData()}>
                  </ListView>
loadingData(){
   pageNum++;
   if(pageNum>Math.ceil(this.state.total/20)){
     return;
   }
    var jsonData = {
      "sessionId": global.appInfo.sessionId,
      "merchName": content,
      "pageNum":pageNum,
    };
    console.log(jsonData)
    Utils.fetchData(this.props.fetchUrl, jsonData, this.SearchCallback);

  }

当ListView和其他子组件在外面加了一个ScrollView时,debugg发现在一直不停地触发onEndReached函数,也就是说父组件ScrollView能滚动,导致ListView中的数据不能满屏,于是就不停地触发该函数,不停fetch请求。

还有,当listView的dataSource第一次渲染时,如果为空,也会触发onEndReached函数,比如我在搜索框输入内容是,因为监听函数的触发,在函数内使用了setState,重新渲染了页面,也是第一次渲染dataSource,于是便会触发onEndReached函数,这样便连续Fetch请求了pageNum=1和pageNum=2

_onChangeText(text) {
    
    pageNum=1;

    if (text) {
      this.setState({ inputValue: text, dataSource: [], recordingIsVisible: false }) //把这行去掉,便不会触发onEndReached函数
      console.log("old id:" + this.settimeId);on
      clearTimeout(this.settimeId);
      content = text;
      this.settimeId = setTimeout(() => {
        var jsonData = {
          "sessionId": global.appInfo.sessionId,
          "merchName": text,
          "pageNum":pageNum,
        };
        Utils.fetchData(this.props.fetchUrl, jsonData, this.SearchCallback);
      }, 1000);
      console.log("sheng chen id:" + this.settimeId);
     

    } else {
      this.setState({ recordingIsVisible: true, inputValue: '' })
    }
  }
<TextInput underlineColorAndroid="transparent" placeholder={"商户简称/全称"} style={{ marginLeft: 10, width: 150 }}
                onChangeText={this._onChangeText.bind(this)}
                value={this.state.inputValue}
                ref="keyWordInput">
              </TextInput>

坑多多,o(╥﹏╥)o

如图模糊搜索



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值