简体   繁体   中英

How to launch function when screen in reached in TabNavigator ? [REACT NAVIGATION]

The problem is that the functions constructor() and componentDidMount() are called when the tab navigator is loaded. And I need to call function each time the user reachs the screen named myScreeen for example How we can do that ?

React-Navigation provides an onNavigationStateChange props that you can use to invoke methods when navigation state change. The screen tracking example showed you an example where you can get the new state's key and route name.

From the example, in the getCurrentRouteName method, you can do const route = navigationState.routes[navigationState.index]; once you retrived the route , you can find out the key and route name by calling route.key and route.routeName .

I found hack :

    <Navigator
    onNavigationStateChange={(prevState, currentState) => {
  const getCurrentRouteName = (navigationState) => {
    if (!navigationState) return null;
    const route = navigationState.routes[navigationState.index];
    if (route.routes) return getCurrentRouteName(route);
    return route.routeName;
  };
  let currentRoute = getCurrentRouteName(currentState);
  if(currentRoute == "A") {
     console.log("TRIGGER")
}}/>;

And then you listen to the log in your component, like this :

  componentDidMount() {
    let slf = this;
    let log = console.log;
    console.log = function(txt) {
      if(txt == "TRIGGER") {
        slf.myFunction();  // CALL HERE YOUR FUNCTION
      } else {
        log.apply(console, arguments);
      }
    }
  }

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