《React-Native系列》19、 ListView組件之上拉重新整理(iOS和Android通用)

來源:互聯網
上載者:User

標籤:

ReactNative提供了RefreshControl下拉重新整理組件,但是沒有提供上拉重新整理組件,上拉重新整理在App中是很常用的。

今天我們來實現一個iOS和Android通用的上拉重新整理功能。

下面簡要介紹下我實現的思路。

如果你對ListView的基礎知識不是很清楚,建議先移步:《React-Native系列》16、 RN組件之ListView


思路:

1、常量定義:

const moreText = "載入完畢";    //foot顯示的文案//頁碼var pageNum = 1;//每頁顯示資料的條數const pageSize = 10;//頁面總資料數var pageCount = 0;//頁面List總資料var totalList = new Array();foot:  0 隱藏  1  已載入完成   2  顯示載入中

2、定義ListView

<ListView    enableEmptySections={true}    dataSource={this.state.dataSource}    renderRow={this._renderRow.bind(this)}    renderFooter={this._renderFooter.bind(this)}    onEndReached={this._endReached.bind(this)}    onEndReachedThreshold={0}/>



3、聲明State狀態機器變數

ListView.DataSource執行個體(列表依賴的資料來源)

  constructor(props) {      super(props);      this.state = {          dataSource: new ListView.DataSource({              rowHasChanged: (r1, r2) => r1 !== r2,          }),         loaded: false,//控制Request請求是否載入完畢         foot:0,// 控制foot, 0:隱藏foot  1:已載入完成   2 :顯示載入中         error:false,}

這裡我們主要聲明了dataSource,這個沒什麼說的

loaded:用來控制整個頁面的菊花

error:如果Request錯誤,顯示一個錯誤頁面

foot: 控制Footer的view


4、渲染頁面前,載入資料

  componentWillMount() {      this._fetchListData();  }

5、Load服務端資料

  _fetchListData() {      if(pageNum > 1){        this.setState({loaded:true});      }      fetch(requestURL, {          method: 'get',          headers: headerObj,      }).then(response =>{        if (response.ok) {            return response.json();        } else {            this.setState({error:true,loaded:true});        }      }).then(<span style="font-family: Arial, Helvetica, sans-serif;">json</span>=>{          let responseCode = json.code;          if (responseCode == 0) {              let responseData = json.data;              <span style="font-family: Arial, Helvetica, sans-serif;">pageCount</span><span style="font-family: Arial, Helvetica, sans-serif;"> = responseData.count;</span>              let list = responseData.data;              if (orderList == null) {                  orderList = [];                  currentCount = 0;              } else {                  currentCount = list.length;              }              if(currentCount < pageSize){                //噹噹前返回的資料小於PageSize時,認為已載入完畢                this.setState({ foot:1,moreText:moreText});              }else{//設定foot 隱藏Footer                 this.setState({foot:0});              }              for (var i=0; i < list.length; i++) {                totalList.push( list[i] );              }               this.setState({                  dataSource: this.state.dataSource.cloneWithRows(totalList),                  loaded: true,              });          }else{              this.setState({error:true,loaded:true});          }      }).catch(function (error) {          this.setState({error:true,loaded:true});      });  }

這裡的細節挺多的:

1、當pageNum > 1時,就不要整個頁面的菊花,此時loaded一直為true,這個主要是為了頁面效果,要不然沒載入一頁資料,這個螢幕就會閃一下。

2、比較當前返回的list的大小,是否小於pageSize,控制Footer是否隱藏,還是顯示已載入完畢

3、聲明了一個全域的totalList對象,每次有新資料的時候,都push進去。

如果不採用push的方式的話,直接採用setState方法的話,第二頁會把第一頁的資料覆蓋掉。


6、定義renderRow方法renderRow={this._renderRow.bind(this)}   列表組件渲染函數 ,此處頁面邏輯省略。


7、定義renderFooter方法

renderFooter   頁尾會在每次渲染過程中都重新渲染。

  _renderFooter() {      if(this.state.foot === 1){//載入完畢        return (          <View style={{height:40,alignItems:'center',justifyContent:'flex-start',}}>              <Text style={{color:'#999999',fontSize:12,marginTop:10}}>                  {this.state.moreText}              </Text>          </View>);      }else if(this.state.foot === 2) {//載入中        return (          <View style={{height:40,alignItems:'center',justifyContent:'center',}}>            <Image source={{uri:loadgif}} style={{width:20,height:20}}/>          </View>);      }  }

根據狀態機器變數foot控制Footer的顯示



8、onEndReached 定義

onEndReachedThreshold={0}

當所有的資料都已經渲染過,並且列表被滾動到距離最底部不足onEndReachedThreshold個像素的距離時調用。原生的滾動事件會被作為參數傳遞。譯註:當第一次渲染時,如果資料不足一屏(比如初始值是空的),這個事件也會被觸發

  _endReached(){    if(this.state.foot != 0 ){      return ;    }    this.setState({      foot:2,    });    this.timer = setTimeout(      () => {        pageNum ++;        this._fetchListData();      },500);  }

這裡需要注意一下幾點

1、第一屏的時候可能也會觸發_endReached方法,所以需要判斷foot為非 0(即載入中和已載入完畢)時,直接return

2、上拉時,觸發_endReached方法,可能server端介面響應很快,幾乎看不到菊花效果,特地加了個500毫秒的等待 


9、卸載Timer

  componentWillUnmount() {  // 如果存在this.timer,則使用clearTimeout清空。  // 如果你使用多個timer,那麼用多個變數,或者用個數組來儲存引用,然後逐個clear    this.timer && clearTimeout(this.timer);  }


待最佳化點:

1、如果ListView的翻頁較多的話,全域變數totalList會非常大,對記憶體是考驗。


如果有問題疑問,可以留言交流。


《React-Native系列》19、 ListView組件之上拉重新整理(iOS和Android通用)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.