【问题标题】:react-native limit List itemsreact-native limit 列出项目
【发布时间】:2018-01-01 13:02:24
【问题描述】:

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

【问题讨论】:

    标签: javascript android reactjs listview react-native


    【解决方案1】:

    基本上,您需要实现分页。您可以使用FlatListonEndReachedonEndReachedThreshold(更多详细信息请查看here)来在用户到达列表末尾时加载更多数据。

    您可以像这样更改代码:

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

    【讨论】:

    • 这不是缺少this.setState({page: page + 1}) 吗?
    猜你喜欢
    • 2019-06-29
    • 2020-09-25
    • 1970-01-01
    • 2022-11-26
    • 1970-01-01
    • 2023-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多