react-native limit 列表项

IT技术 javascript android reactjs listview react-native
2021-05-01 07:48:55

我正在使用来自 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个回答

基本上,您需要的是实现某种分页。当用户到达列表末尾时,您可以使用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>
    );
  }
}