简体   繁体   English

在React Native的当前屏幕上显示时,如何主动刷新FlatList?

[英]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. 我正在使用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. 我使用<FlatList>作为主屏幕上的聊天频道列表,并且使用StackNavigator进行屏幕之间的导航。 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. 现在,我试图让<FlatList>从后端重新获取数据并在用户导航回到主屏幕时重新呈现自身。

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. 一个示例是,用户进入一个聊天频道,该应用程序导航到聊天详细信息屏幕,该用户向其中发送一些消息,当用户按下“后退”按钮并导航回到主聊天频道列表屏幕时, <FlatList>应该从后端重新执行并重新渲染以显示最新数据。 (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. 现在实现了刷新刷新,但问题是我如何知道用户已导航回主屏幕,以及如何在刷新时主动调用<FlatList>上的刷新。

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: 导航到ChatDetails屏幕时,可以将回调作为导航参数传递:

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. 因此,而不是console.log() ,请执行fetch()或/和其他操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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