我使用的是反应原生的Flatlist和反应原生元素的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><ListItemsubTitle={<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> ) }}
解决方法:
基本上,你需要的是实现一种分页.您可以使用onEndReached和onEndReachedThreshold(有关详细信息,请查看here)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 somewhereconst 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> ); }}
总结 以上是内存溢出为你收集整理的javascript – react-native limit列出项目全部内容,希望文章能够帮你解决javascript – react-native limit列出项目所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)