简体   繁体   中英

How to actively refresh a FlatList whenever it shows on the current screen in React Native?

I'm creating a live chat app using React Native. I'm using <FlatList> for the chat channel list on the main screen, and I'm using StackNavigator for the navigation between screens. Now I am trying to let the <FlatList> refetch data from the back-end and rerender itself whenever user navigate back to the main screen.

An example will be a user enters a chat channel, the app navigates to the chat detail screen, the user sends some messages there, when the user press the back button and navigates back to the main chat channel list screen, the <FlatList> should refectch from the back-end and rerender itself to show the latest data. (reorder the most recent channel to the top etc.)

Right now pull to refresh is implemented but the problem is how do I know that the user has navigated back to the main screen and how to actively call refresh on <FlatList> when that happens.

Here is some of my code:

  onRefresh = async () => { const { data } = this.props try { this.setState({ refreshing: true }) await data.refetch({ page: 1 }) } catch (e) { // todo } finally { this.setState({ refreshing: false, }) } } const NudgeList = ({ nudges, loading, refreshing, onRefresh, }) => { let inner if (loading && !refreshing && !fetchingMore) { inner = ( <View style={styles.center}> <ActivityIndicator animating /> </View> ) } else { inner = ( <FlatList onRefresh={onRefresh} refreshing={refreshing || false} scrollEventThrottle={400} data={nudges} renderItem={({ item }) => ( <NudgeCard nudge={item} {...{ onOpenNudge }} /> )} /> ) } return ( <View style={styles.container}> {inner} </View> ) } 

You can pass a callback as a navigation param when you navigate to the ChatDetails screen:

this.props.navigation.navigate(
  'ChatDetails', 
  {
    onGoBack: () => console.log('Will go back from ChatDetails'),
  }
);

So, instead of console.log() , do your fetch() or/and whatever you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM