简体   繁体   中英

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

I will try to explain my case:

I have 2 pages/screens

SreenA.js :

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

ScreenB.js :

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

What i want to achieve :

When i press back button in screenB , my app will back to screenA. When i come back to screenA , i need to refresh the FlatList. (each time i back to screenA).

How i achieve that case in Android Native ?

I add this section to help you to more understand what challenge i face. In Android Native, i will use onResume to refresh the list (onResume called everytime the screen/page called).

What i already try but not work for me now :

I already try this but what i get it just called when app in background and then show in foreground :

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

Add navigation.addListener to fire every time a page receives navigation focus.

As an example:

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

For the full example, check the following snack on your phone. The timestamp will update every time you navigate back to page 1 but not when the app resumes.

You should be able to expand it for your needs from this example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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