onEndReached函数在FlatList(react-native)中多次调用

时间:2020-04-05 15:54:21

标签: react-native react-native-flatlist

在我的代码中,loadAlbums方法首次正确运行。为什么我向下滚动retrieveMore函数调用几次。

const PAGE_SIZE = 15;
const App = () => {

  const [albums, setAlbums] = useState([]);
  const [page, setPage] = useState(1);

  const loadAlbums = async () => {
    const response = await axios.get(`http://xxx:3000/posts/${PAGE_SIZE}/${page}`);
    setAlbums([...albums, ...response.data]);
    setPage(page + 1)
  }

  useEffect(() => {
    loadAlbums();
  }, [])



  const renderRowItem = ({ item }) => {
    return (
      <View style={styles.item}>
        <Text>{item.id}</Text>
        <Text>{item.body}</Text>
      </View>
    )
  }

  const retrieveMore = useCallback(() => {
    loadAlbums(); //  this line calls several times
  })

  return (
    <View style={styles.screen}>
      <FlatList
        data={albums}
        renderItem={renderRowItem}
        keyExtractor={(item, index) => index.toString()}
        onEndReached={retrieveMore}
        onEndReachedThreshold={0.5}
      />
    </View>
  )
}

1 个答案:

答案 0 :(得分:0)

只需降低阈值

onEndReachedThreshold = {0.5} onEndReachedThreshold = {0.2}

当前,每次到达屏幕的50%时,将在这里发生什么事。