【问题标题】:React Native - How to refresh FlatList when back to previous page?React Native - 返回上一页时如何刷新 FlatList?
【发布时间】:2018-10-27 16:06:33
【问题描述】:

我会尝试解释我的情况:

我有 2 个页面/屏幕

SreenA.js:

...
<FlatList>
</FlatList>
...

ScreenB.js:

...
<Button> This button for back to ScreenA </Button>
...

我想要达到的目标:

当我在 screenB 中按下返回按钮时,我的应用程序将返回到 screenA。 当我回到 screenA 时,我需要刷新 FlatList。 (每个 时间我回到屏幕A)。

我如何在 Android Native 中实现这种情况?

我添加此部分是为了帮助您更了解我面临的挑战 脸。在 Android Native 中,我将使用 onResume 刷新列表 (每次调用屏幕/页面时都会调用 onResume)。

我已经尝试过但现在不适合我的方法:

我已经尝试过了,但是当应用程序在后台运行然后在前台显示时我得到它的调用:

state = {
    appState: AppState.currentState
  }

  componentDidMount() {
    AppState.addEventListener('change', this._handleAppStateChange);
  }

  componentWillUnmount() {
    AppState.removeEventListener('change', this._handleAppStateChange);
  }

  _handleAppStateChange = (nextAppState) => {
    if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
      console.log('App has come to the foreground!')
      //i place the code here for refresh the flatList. But not work
    }
    this.setState({appState: nextAppState});
  }

【问题讨论】:

  • 你用什么导航?
  • 我使用 StackNavigator
  • 使用onWillFocusnavigation event
  • 你能给我举个例子吗?如果有效,我将接受正确答案。

标签: javascript android react-native


【解决方案1】:

添加navigation.addListener 以在每次页面获得导航焦点时触发。

举个例子:

class Page1 extends React.Component {
  constructor(props) {
    super(props);
    this.state = { ts: 0 }

    // this will fire every time Page 1 receives navigation focus
    this.props.navigation.addListener('willFocus', () => {
      this.setState({ ts: Date.now() })
    })
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.paragraph}>
          Page 1 [{this.state.ts}]
        </Text>
        <Button title="Page 2" onPress={() => this.props.navigation.navigate('Page2')}/>
      </View>
    );
  }
}

如需完整示例,请在您的手机上查看以下snack。时间戳会在您每次导航回第 1 页时更新,但不会在应用恢复时更新。

您应该能够根据此示例扩展它以满足您的需要。

【讨论】:

  • 这会导致内存问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-04
  • 2018-12-14
  • 2018-03-26
  • 1970-01-01
  • 2018-09-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多