FlatList在到达底部时调用On Load(React Native)

6

当我在FlatList中使用onEndReached函数时,它会自动调用。

以下是此问题的链接。

链接

是否有可用的解决方案或iOS中的替代方法?

编辑:

以下是我尝试的代码,但似乎不起作用。

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

    loadMore(){
        if(!this.state.flatListReady){
            return null;
        }
        else{
            alert("End Reached")
        }
    }

    _scrolled(){
        this.setState({flatListReady:true});
    }

    render() {
        return (
            <Layout style={{ flex: 1 }}>

                <FlatList
                    data={listData}
                    renderItem={({item}) => this._renderItem(item)}
                    keyExtractor={(item, index) => item.key}
                    onEndReached={() => this.loadMore()}
                    onEndReachedThreshold={0.5}
                    onScroll={() => this._scrolled()}
                />

            </Layout>

删除 onScroll。 - Gokul Kulkarni
并在 this.loadMore() 周围添加大括号 {}。 - Gokul Kulkarni
Gokul,它仍然不起作用。 - Shubham Bisht
将 renderItem={({item}) => this._renderItem(item)} 转换为 renderItem={this._renderItem},然后在 renderItem 内部进行解构。 - Gokul Kulkarni
还是不起作用 :( - Shubham Bisht
显示剩余6条评论
3个回答

14

试试这个,

onEndReachedThreshold={0.5}
onEndReached={({ distanceFromEnd }) => {
if(distanceFromEnd >= 0) {
     //Call pagination function
}
}}

3
无效。onEndReached函数内的任何内容都会在组件的onLoad中被调用。 - Shubham Bisht

6
有时候事情并不像它们应该的那样工作,毕竟这不是原生代码,所以可能是您组件的顺序或者Flatlist封装在一个非预期组件中,或者是某些属性应该传递给Flatlist组件本身才能正确激活onEndReached回调。
我自己也遇到过这个问题,我不知道该怎么做才能使它正常工作。
一个很好的解决方法来源于Flatlist继承了ScorllView属性。因此,您可以使用onScroll属性来检测是否已到达末尾。
<FlatList
    data={this.props.dashboard.toPreviewComplaints}
    onScroll={({nativeEvent})=>{
        //console.log(nativeEvent);
        if(!this.scrollToEndNotified && this.isCloseToBottom(nativeEvent)){
             this.scrollToEndNotified = true;
             this.loadMoreData();
        }
    }}
/>

this.scrollToEndNotified 作为一个标记来防止滥用对 loadMore 终点的调用。

isCloseToBottom({layoutMeasurement, contentOffset, contentSize}){
    return layoutMeasurement.height + contentOffset.y >= contentSize.height - 100;
}

无论何时成功调用了 isCloseToBottom,这表示您已经到达列表末尾,因此您可以调用 loadMoreData 函数。

-3

非常小心地处理这个函数,

  endReached=()=>{
          //take care of ES6 Fat arrow function and trigger your conditions properly with current state and new state data or current state with new Props.
    Based on those conditions only, you need to trigger the other API call

    }

<FlatList data={this.state.data}
     extraData={this.state.load}
     renderItem={this.renderCard}
     keyExtractor={item => item.fundRequestId}
     onEndReached={this.endReached}
     onEndReachedThreshold={.7}
     ListFooterComponent={this.renderFooter}
     />

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接