androidreact-nativereact-navigationtabnavigator

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 ?


Solution

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