簡體   English   中英

react-native limit列表項

[英]react-native limit List items

我正在使用來自react-native的Flatlist和來自react-native-elements的ListItem

我想最初限制屏幕上加載的列表項的數量。否則它會加載我最初的所有項目。

假設我有300個列表項,但最初我只想加載10個項目,而不是300個。

我的代碼:

import React, { Component } from 'react'
import {
   FlatList
} from 'react-native'

import {Avatar,Tile,ListItem} from 'react-native-elements'

export default class Login extends Component{
constructor(props) {
    super(props);


this.state = {
  data:[],
   dataSource: []

    };
  }


renderList(item,i){


  return(

<View>
<ListItem

subtitle={
<Avatar
  small
  rounded
  source={{uri: "https://s3.amazonaws.com/uifaces/faces/twitter/ladylexy/128.jpg"}}

/>
{<Text>{item.body}</Text>}
}

/>
<View>
    )
}

render(){  
    return( 
        <View>
<List>
<FlatList
        data={this.state.data}
        keyExtractor={item => item.id}
        renderItem ={({item,index}) => this.renderList(item,index)}
      />
</List>  
</View>
      )
  }
}

基本上,你需要的是實現一種分頁。 您可以使用onEndReachedonEndReachedThreshold (有關詳細信息,請參見此處FlatList以便在用戶到達列表末尾時加載更多數據。

您可以像這樣更改代碼:

import React, { Component } from 'react';
import { FlatList } from 'react-native';

import { Avatar, Tile, ListItem } from 'react-native-elements';

const initialData = [0,...,299]; //all 300. Usually you receive this from server or is stored as one batch somewhere
const ITEMS_PER_PAGE = 10; // what is the batch size you want to load.
export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      data: [0,..., 9], // you can do something like initialData.slice(0, 10) to populate from initialData.
      dataSource: [],
      page: 1,
    };
  }

  renderList(item, i) {
    return (
      <View>
        <ListItem />
      </View>
    );
  }

  loadMore() {
    const { page, data } = this.state;
    const start = page*ITEMS_PER_PAGE;
    const end = (page+1)*ITEMS_PER_PAGE-1;

    const newData = initialData.slice(start, end); // here, we will receive next batch of the items
    this.setState({data: [...data, ...newData]}); // here we are appending new batch to existing batch
  }


  render() {
    return (
      <View>
        <FlatList
          data={this.state.data}
          keyExtractor={item => item.id}
          renderItem={({ item, index }) => this.renderList(item, index)}
          onEndReached={this.loadMore}
        />
      </View>
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM