📌  相关文章
📜  flatlist onrefresh react native - Javascript (1)

📅  最后修改于: 2023-12-03 14:41:13.738000             🧑  作者: Mango

FlatList onRefresh React Native

If you're developing an app using React Native, you're likely familiar with the FlatList component, a highly performant way to render a list of data. The FlatList component provides a way to load data dynamically using pagination, and also supports onEndReached for triggering a load when the user scrolls to the end of the list.

In addition to these features, FlatList also supports a pull-to-refresh functionality using the onRefresh prop.

To implement this, you'll need to define a function that will be called when the user pulls to refresh. This function will typically make an API call to retrieve new data and update the component state accordingly.

Here's an example of a basic implementation of onRefresh:

import React, { useState } from 'react';
import { FlatList, RefreshControl, Text, View } from 'react-native';

const DATA = ['Item 1', 'Item 2', 'Item 3', 'Item 4', 'Item 5'];

const FlatListDemo = () => {
  const [refreshing, setRefreshing] = useState(false);

  const onRefresh = () => {
    setRefreshing(true);

    // Make API call or update data here...

    setTimeout(() => {
      setRefreshing(false);
    }, 2000);
  };

  return (
    <FlatList
      data={DATA}
      renderItem={({ item }) => (
        <View>
          <Text>{item}</Text>
        </View>
      )}
      refreshControl={
        <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
      }
    />
  );
};

export default FlatListDemo;

In this example, we define a simple list of data and use useState to manage the refreshing state. The onRefresh function is called when the user pulls to refresh, and in this case, we're simply setting a timeout to simulate an API call.

We pass the refreshing state to the RefreshControl component, which renders a spinner while refreshing is true. Once the mock API call is complete, we set refreshing back to false, and the spinner disappears.

That's it! With just a few lines of code, you've added pull-to-refresh functionality to your FlatList component in React Native using the onRefresh prop.