關於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

如圖模糊搜索



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章