Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Navigation: Navigate Back To Root using NavigationActions.reset, goBack and getStateForAction

Say I've navigated through 4 screens in my StackNavigator App and now I want to go back to the first screen. There seems to be three different ways to do this and they do navigate to where I want to do, however each way has an animation that cycles through each previous screen.

Is there a clean way to navigate from SCREEN_D to SCREEN_A?

In other words, I don't want to see SCREEN_C and SCREEN_B a split of a second before seeing SCREEN_A when navigating backwards from SCREEN_D

navigation.navigate(SCREEN_A); ... navigation.navigate(SCREEN_B); ... navigation.navigate(SCREEN_C); ... navigation.navigate(SCREEN_D); 

Three ways to do this:

1.

return this.props.navigation                .dispatch(NavigationActions.reset(                  {                     index: 0,                     actions: [NavigationActions.navigate({ routeName: 'SCREEN_A'})]                   })); 

2.

 const {SCREEN_B_KEY} = this.props.navigation.state.params  this.props.navigation.goBack(SCREEN_B_KEY) 

3.

const defaultGetStateForAction = Navigation.router.getStateForAction;  Navigation.router.getStateForAction = (action, state) =>{   if(action.type === "Navigation/BACK"){     const routes = [       {routeName: 'First'},     ];     return {       ...state,       routes,       index: 0,     };   }   return defaultGetStateForAction (action,state); } 
like image 828
Turnipdabeets Avatar asked May 12 '17 21:05

Turnipdabeets


People also ask

How do I reset the navigation stack in react navigation?

To reset the navigation stack for the home screen with React Navigation and React Native, we can use the navigation. dispatch and the CommonActions. reset methods. import { CommonActions } from "@react-navigation/native"; navigation.

What does navigation Reset do?

The Reset action wipes the whole navigation state and replaces it with the result of several actions. index - number - required - Index of the active route on routes array in navigation state . actions - array - required - Array of Navigation Actions that will replace the navigation state.

How do I go back to previous screen in react?

Use the goBack() Method to Go Back One Screen in React Native. The goBack() method is one of the most important methods in the react-navigation library. It allows you to go back to one of the previous screens in your navigation stack.


1 Answers

react-navigation has popToTop and we can use it like blow

this.props.navigation.popToTop() 
like image 148
Sultan Ali Avatar answered Sep 24 '22 17:09

Sultan Ali