React Navigation check if previous screen exists

后端 未结 5 727
甜味超标
甜味超标 2020-12-10 16:37

I am looking desperately for a possibility to check if a previous screen exists in ReactNavigation.

Using this.props.navigation.goBack() returns

相关标签:
5条回答
  • 2020-12-10 16:56

    As of React Navigation 5 you can use useNavigationState hook inside functional component this way:

    const routesLength = useNavigationState(state => state.routes.length);
    console.log('routesLength', routesLength);
    

    If routesLength > 1 then it is not the first screen in stack

    Or you can use navigation.canGoBack()

    0 讨论(0)
  • 2020-12-10 17:09

    It's completely working for me.... If you want to find out previous route/screen name from navigation stack in react native app so you can use this function.

    export const previousRouteName = (navigation) =>{
      let navRoutes = navigation.dangerouslyGetParent().state.routes;
      if (navRoutes.length >= 2){
        return navRoutes[navRoutes.length - 2].routeName
      }
      return navigation.state.routeName
    }
    

    How to use?

    previousRouteName(props.navigation);
    

    Hope you like and helpful to you K00L ;)

    0 讨论(0)
  • 2020-12-10 17:10

    What could be a solution (not sure that it's the best one) would be to spend in the param object the previous screen. With that, if the params exists would mean that a previous screen exists.

    For example:

    const navigateAction = NavigationActions.navigate({
      routeName: 'Profile',
    
      params: { previous_screen: 'CURRENT_SCREEN' },
    
      action: NavigationActions.navigate({ routeName: 'NEXT_SCREEN' }),
    });
    
    this.props.navigation.dispatch(navigateAction);
    

    And then in the next screen:

    const { navigation } = this.props;
    if (navigation.state.params && navigation.state.params.previous_screen) {
      // A previous screen exists
    } else {
      // No previous screen
    }
    
    0 讨论(0)
  • 2020-12-10 17:14
    const navigateAction = NavigationActions.navigate({
      routeName: 'NEXT_SCREEN',
      action: NavigationActions.navigate({ routeName: 'NEXT_SCREEN', params: { previous_screen: 'CURRENT_SCREEN' } }),
    });
    this.props.navigation.dispatch(navigateAction);
    
    0 讨论(0)
  • 2020-12-10 17:15

    There is an easier way:

    if(this.props.navigation.isFirstRouteInParent()) {
        //a previous screen does not exist
    } else {
        //a previous screen does exist
    }
    
    0 讨论(0)
提交回复
热议问题