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

邮差的信 提交于 2019-12-10 11:46:16

问题


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>
  )
}

回答1:


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.



来源:https://stackoverflow.com/questions/46738263/how-to-actively-refresh-a-flatlist-whenever-it-shows-on-the-current-screen-in-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!