react-native limit 列表项

2024-04-26

我在用Flatlist https://facebook.github.io/react-native/docs/flatlist.html来自反应本机和ListItem https://react-native-training.github.io/react-native-elements/API/lists/来自反应本机元素,

我想最初限制屏幕上加载的列表项的数量。否则它将加载我最初拥有的所有项目。

假设我有 300 个列表项,但最初我只想加载 10 个项目,而不是 300 个。

MY CODE:

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>
      )
  }
}

基本上,您需要的是实现某种分页。你可以通过使用来做到这一点onEndReached and onEndReachedThreshold(更多详情请看here https://facebook.github.io/react-native/docs/flatlist.html#onendreachedthreshold) of 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>
    );
  }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

react-native limit 列表项 的相关文章

随机推荐