首页 > 解决方案 > How i can limit the items in the FlatList and add load more?

问题描述

My skills is basic, and i'm newbie in React native, what i want to do is limit the posts in 12 and when the user scroll automatically load more posts.

My Code:

export default class Posts extends Component {
constructor(props) {
super(props);
this.state = {
  isLoading: true,};}

componentDidMount() {
   return fetch(ConfigApp.URL+'json/data_posts.php')
     .then((response) => response.json())
     .then((responseJson) => {
       this.setState({
         isLoading: false,
         dataPosts: responseJson
       }, function() {
       });
     })
     .catch((error) => {
     });}

render() {
return (
    <FlatList
      data={ this.state.dataPosts }
      numColumns={2}
      renderItem={({item}) => 
            <TouchableOpacity activeOpacity={1} style={{flex: 1}}>
            <View style={{margin: 5, marginLeft: 4}}>
            <ImageBackground source={{uri: ConfigApp.IMAGESFOLDER+item.post_image}}>
                <LinearGradient colors={['rgba(0,0,0,0.3)', 'rgba(0,0,0,0.8)']}>
                        <Text numberOfLines={2}>{item.post_title}</Text>
                </LinearGradient>
            </ImageBackground>
            </View>
            </TouchableOpacity>
}
    keyExtractor={(item, index) => index}

    />
);}}

标签: reactjsreact-native

解决方案


如果您的要求是将现有列表从已提取的数据中追加到 12 块中,那么您可以考虑使用以下策略来处理滚动onEndReachedonEndThreshold一次添加 12 条记录。

在构造函数中设置当前page数字0

constructor(props){
  super(props);
  this.state = {
    ... ,
    page: 0,
    posts: []
  }
}

在内部componentDidMount,您需要从服务器中提取所有数据并将其存储在本地状态(您当前正在执行的操作)中,然后调用将读取前 12 条记录的函数。

componentDidMount() {
   return fetch(ConfigApp.URL+'json/data_posts.php')
   .then((response) => response.json())
   .then((responseJson) => {
     this.setState({
       isLoading: false,
       page: 0,
       dataPosts: responseJson
     }, function() {
       // call the function to pull initial 12 records
       this.addRecords(0);
     });
   })
   .catch((error) => {
   });
}

现在添加将添加记录的功能this.state.dataPosts

addRecords = (page) => {
  // assuming this.state.dataPosts hold all the records
  const newRecords = []
  for(var i = page * 12, il = i + 12; i < il && i < 
    this.state.dataPosts.length; i++){
    newRecords.push(this.state.dataPosts[i]);
  }
  this.setState({
    posts: [...this.state.posts, ...newRecords]
  });
}

现在添加滚动处理程序

onScrollHandler = () => {
  this.setState({
    page: this.state.page + 1
  }, () => {
    this.addRecords(this.state.page);
  });
}

渲染功能

render() {
  return(
    ...
    <FlatList
       ...
       data={this.state.posts}
       renderItem={({item}) => ... }
       keyExtractor={(item, index) => index}
       onEndReached={this.onScrollHandler}
       onEndThreshold={0}
    />
    ...
  );
}

希望这会有所帮助!


推荐阅读