簡體   English   中英

當我們到達列表底部時,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 = () => {
    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
            });  
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM