ReactNative Flatlist onEndReached不起作用

时间:2017-11-17 13:19:33

标签: reactjs react-native react-native-flatlist

我试图在FlatList的onEndReached上调用一个函数,但它无效。

我在最后调用this.state.pageNo并且它没有更新。我想稍后在无限滚动中使用这个逻辑,但现在无法使它工作。

 import React, { Component } from "react";
 import {
  View,
  Text,
  StyleSheet,
  Button,
  TouchableOpacity,
  FlatList,
  Alert
  } from "react-native";

 class InfiniteScrollRedux extends Component {
   constructor(props) {
      super(props);
      this.state = {
        loading: false,
        pageNo: 1,
        data: [
            { id: 1, name: "Name01" },
            { id: 2, name: "Name02" },
            { id: 3, name: "Name03" },
            { id: 4, name: "Name04" },
            { id: 5, name: "Name05" },
            { id: 6, name: "Name06" }
        ]
    };
}

myFunction = () => {
    this.setState({ pageNo: this.state.pageNo++ });
};

render() {
    return (
        <View>
            <FlatList
                data={this.state.data}
                renderItem={({ item }) => (
                    <View style={mystyle.mainCard}>
                        <Text style={mystyle.titleText}> {item.id} </Text>
                        <View style={{ marginTop: 200 }} />
                        <Text style={mystyle.nameText}> {item.name} </Text>
                    </View>
                )}
                keyExtractor={item => item.id}
                onEndReached={this.myFunction}
                onEndThreshold={0}
            />
            <Text style={{ margin: 20, padding: 20, fontSize: 20 }}>
                {this.state.pageNo}
            </Text>
        </View>
      );
   }
}

const mystyle = StyleSheet.create({
 mainCard: {
    backgroundColor: "#2F4F4F",
    marginBottom: 1,
    padding: 5
},
titleText: {
    fontSize: 20,
    color: "#F0FFFF"
},
nameText: {
    fontSize: 14,
    color: "#F0FFFF"
 }
 });

 export default InfiniteScrollRedux;

5 个答案:

答案 0 :(得分:7)

这里有一个问题:https://github.com/facebook/react-native/issues/14312。看起来很多人都在经历同样的事情。有人建议将onEndReachedThreshold更改为大于0的值,例如:0.3。

答案 1 :(得分:5)

在我的情况下,问题出在本机库<Content>上。在其中使用<FlatList>时会产生问题。解决方案:

<Content
  style={{flex: 1}}
  contentContainerStyle={{flex: 1}} // important!
>

来源:https://github.com/GeekyAnts/NativeBase/issues/1736

答案 2 :(得分:1)

您在FlatList中寻找的属性是onEndReachedThreshold而不是onEndThreshold。

答案 3 :(得分:1)

首先,您应该确保onEndReached听取onMomentumScrollBegin的{​​{1}}和onMomentumScrollEnd道具。另一个重要的事情是FlatList distanceFromEnd onEndReached道具FaltList。所以你可以按如下方式使用它:

          onMomentumScrollBegin={() => this.setState({ scrollBegin: true })}
          onMomentumScrollEnd={() => this.setState({ scrollBegin: false })}
          onEndReached={({ distanceFromEnd }) =>
            distanceFromEnd<=0.5&&
            this.state.scrollBegin &&
            this.onEndReached()
          }

然后您可以定义onEndReached函数,该函数将根据需要运行。

希望这可以帮助别人节省时间。

答案 4 :(得分:0)

被这个问题困扰了很长时间。我认为 React 在计算屏幕高度与容器高度时存在混淆。 所以我们能做的最好的事情是将 onEndReachedThreshold 值增加到高于 0 到某个 0.2, 0.4 等。