繁体   English   中英

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

[英]React Native - How to refresh FlatList when back to previous page?

我会尝试解释我的情况:

我有2页/屏幕

SreenA.js:

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

ScreenB.js:

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

我想要实现的目标:

当我按下screenB中的后退按钮时,我的应用程序将返回到screenA。 当我回到screenA时,我需要刷新FlatList。 (每次我回到screenA)。

我如何在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});
  }

添加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>
    );
  }
}

有关完整示例,请在手机上查看以下小吃 每次导航回第1页时,时间戳都会更新,但不会在应用程序恢复时更新。

您应该可以从此示例中根据需要扩展它。

暂无
暂无

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

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