当我们到达列表底部时,React Native FlatList 加载更多

React Native FlatList load more when we get to the bottom of the list

如何使用 React Native 的 FlatList 增加负载 (不是无限的)

我已经这样做了,但不幸的是它会无限加载。

这是我的代码片段

<FlatList
    data={this.props.data}
    renderItem={({ item, separators }) => (
        <TouchableHighlight
            onPress={() => this._onPress(item)}
            onShowUnderlay={separators.highlight}
            onHideUnderlay={separators.unhighlight}
        >
            <Text> {item.title} </Text>
        </TouchableHighlight>
    )}
    keyExtractor={item => item.id}
    ListFooterComponent={this.renderFooter}
    onEndReached={this.props.handleLoadMore}
    onEndThreshold={0}
/>

还有我的 handleLoadMore

handleLoadMore = () => {
    console.log("test"); // <---- this line run infinitely
    fetch(url, {
        method: "POST",
        headers: {
            Accept: "application/json",
            "Content-Type": "application/json"
        },
        body: JSON.stringify(filters)
    })
        .then(response => response.json())
        .then(responseJson => {
            this.setState({
                itemData: [
                    ...this.state.itemData,
                    ...responseJson.estate_list
                ],
                itemPage: this.state.itemPage + 1
            });
        })
        .catch(error => {
            console.error(error);
        });
};

在 FlatList 中加载数据时出现问题,您的 onEndReached 处理程序将在重新呈现视图时被调用。尝试像这样设置一个标志:

constructor(props){
  super(props);
  this.state = {
    hasScrolled: false
  }
}

然后添加这个方法:

onScroll = () => {
 this.setState({hasScrolled: true})
}

将其连接到 FlatList:

<FlatList
onScroll={this.onScroll}

最终只在滚动时加载:

handleLoadMore = () => {
  if(!this.state.hasScrolled){ return null; }

  //here load data from your backend

}
constructor(props){
  super(props);
  this.state = {
    loading: true
  }
}

   <FlatList  
 onEndReached={this.handleLoadMore}/>

 handleLoadMore = () => {
        if(!this.state.loading){ return null; }
        
        this.setState({
        page: this.state.page + 1,
        loading: false
        }, () => {
        this.loadProducts(); 
        });
    };

 loadProducts(catId,userkey){
          $this.setState({ 
                loading:true
            });  
    }