React native infinite scroll with flatlist

后端 未结 3 1264
鱼传尺愫
鱼传尺愫 2020-12-04 01:45

I followed this tutorial https://www.youtube.com/watch?v=rY0braBBlgw When I scroll down it sends the request then it gets stuck in a loop and just requests and requests. I t

3条回答
  •  情歌与酒
    2020-12-04 02:29

    This works for me:

          renderItem(item, index)}
              keyExtractor={(item, index) => item.id.toString()}
              onEndReached={this.fetchMore}
              onEndReachedThreshold={0.1}
              ListFooterComponent={this.renderFooter}
              refreshing={this.state.refreshing}
            />
    
    
    renderFooter = () => {
        if (this.state.refreshing) {
          return ;
        } else {
          return null;
        }
      };
    
    
      fetchMore = () => {
        if (this.state.refreshing){
          return null;
        }
        this.setState(
          (prevState) => {
            return { refreshing: true, pageNum: prevState.pageNum + 1 };
          },
          () => {
            this.sendAPIRequest(null , true);
          }
        );
      };
    

    The reason I used the following in the fetchMore function:

    if (this.state.refreshing){
          return null;
        }
    

    Is because when you setState to the pageNum it calls the render() function and then the fetchMore called again. This is written to prevent it. In addition, I set:

    refreshing: false
    

    after the sendAPIRequest is done. Pay attention about onEndReachedThreshold in FlatList:

    How far from the end (in units of visible length of the list) the bottom edge of the list must be from the end of the content to trigger the onEndReached callback.

    Meaning in my example (0.1) means: when you reach 10% of items from the bottom, the fetchMore callback is called. In my example, I have 10 items in the list, so when the last item is visible, fetchMore is called.

提交回复
热议问题