简体   繁体   中英

how to take an action when user enters a screen or navigates away from it?

This is my app container:

const AppNavigator = createBottomTabNavigator({
    createUser: CreateUser,
    showUsers: ShowUsers,
    editUser: EditUser
});

in createUser I make new users and save them in my database, and in showUsers on componentDidMount lifecycle I get the data from my database and list them. but since screens don't unmount when we navigate away from them, the componentDidMount lifecycle is just called the first time, so each time I get previews data, and I have to reload my app to see the result. how can I solve this?

React navigation has a lifecycle api, to do exactly what you describe:

For more information check the docs: https://reactnavigation.org/docs/en/navigation-lifecycle.html

Part of that API is a withNavigationFocus HOC, and this provides an isFocused prop which indicates if a screen is visible.

Example:

import { withNavigationFocus } from 'react-navigation';

class SomeScreen extends React.Component {

  componentDidUpdate(prevProps) {
    if (this.props.isFocused && !prevProps.isFocused) {
      // Screen has now come into focus
    }
  }

}

export default withNavigationFocus(SomeScreen)

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