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

时间:2018-07-10 10:19:07

标签: react-native react-native-flatlist

如何使用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);
        });
};

2 个答案:

答案 0 :(得分:10)

在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

}

答案 1 :(得分:1)

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