Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Navigation, how to go back to specific screens?

I'm using react-navigation:^1.0.0-beta.9 is there a way to go back to specific screen (not the previous one to the current)? I've also integrated my react-navigation with redux. I've looked into the documentation and saw that back accepts a key param however this is unclear to me and tried placing in the name of the Screen like back({ key: 'Screen B' }) but it doesn't work probably because it's expecting a key which is randomly generated unless specified specifically.

For example I have this StackNavigator

Screen A
- Screen B
  - Screen C
    - Screen D (Current)

Let's say I am currently on Screen D and I wanted to go back to Screen B how would I achieve it?

I don't want to use navigation.navigate('Screen B') because that's gonna add another screen to the stack and not what I'm expecting.

like image 941
JohnnyQ Avatar asked Dec 05 '22 14:12

JohnnyQ


1 Answers

1.Inside screen D dispatch some action:

    const {navigation} = this.props;
    navigation.dispatch({
        routeName: 'B',
        type: 'GoToRoute',
    });

2.Handle this action in MyStackNavigator.js

const MyStackNavigator = new StackNavigator(//...);
const defaultGetStateForAction = MyStackNavigator.router.getStateForAction;
MyStackNavigator.router.getStateForAction = (action, state) => {            
    if (state && action.type === 'GoToRoute') {           
        let index = state.routes.findIndex((item) => {
            return item.routeName === action.routeName
        });
        const routes = state.routes.slice(0, index+1);
        return {
            routes,
            index
        };    
    }       
    return defaultGetStateForAction(action, state);
};

and then you can go from screen D to screen B directly

like image 135
ufxmeng Avatar answered Dec 17 '22 05:12

ufxmeng