如何在React Native中显示当前屏幕时主动刷新FlatList? [英] How to actively refresh a FlatList whenever it shows on the current screen in React Native?

查看:248
本文介绍了如何在React Native中显示当前屏幕时主动刷新FlatList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React Native创建一个实时聊天应用。
我在主屏幕上的聊天频道列表中使用< FlatList> ,我正在使用 StackNavigator 屏幕之间的导航。
现在我试图让< FlatList> 从后端重新获取数据,并在用户导航回主屏幕时重新呈现。

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.

一个例子是用户进入聊天频道,应用程序导航到聊天详细信息屏幕,用户在那里发送一些消息,当用户按下后退按钮并导航回到主聊天频道列表屏幕,< 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. (reorder the most recent channel to the top etc.)

现在执行pull to refresh但问题是如何知道用户已导航回到主屏幕以及当发生这种情况时如何主动调用< FlatList> 上的刷新。

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.

这是我的一些代码:

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

推荐答案

您可以将回调作为导航参数传递给您导航到ChatDetails屏幕:

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'),
  }
);

所以,而不是 console.log(),你的 fetch()或/和你想要的任何东西。

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

这篇关于如何在React Native中显示当前屏幕时主动刷新FlatList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆