React Native - 如何在返回到前一页时刷新FlatList?

6
我会尽力解释我的情况:
我有两个页面/屏幕
SreenA.js:
...
<FlatList>
</FlatList>
...

ScreenB.js :

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

我想要实现的目标:

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

如何在Android原生中实现这种情况?

我添加了这个部分来帮助你更好地理解我面临的挑战。在Android原生中,我将使用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});
  }

你在使用什么进行导航? - Wainage
我使用StackNavigator。 - Crocodile
使用 onWillFocus 导航事件 - Wainage
你可以给一个例子吗?如果它能用,我就接受作为正确答案。 - Crocodile
1个回答

4

添加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页时,时间戳将更新,但应用程序恢复时不会更新。

您应该能够从此示例中扩展其功能以满足您的需求。


这会导致任何内存问题吗? - PvUIDev

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接