react-native limit列表项

时间:2017-07-26 09:35:17

标签: javascript android reactjs listview react-native

我正在使用来自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>
      )
  }
}

1 个答案:

答案 0 :(得分:7)

基本上,你需要的是实现一种分页。您可以使用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> ); } } 的更多详细信息,以便在用户到达列表末尾时加载更多数据。

您可以像这样更改代码:

kubectl patch