React Navigation how to get back to specific screens?

I am using react-navigation:^1.0.0-beta.9

, is there a way to go back to a specific screen (and not the previous one)? I also integrated mine react-navigation

with redux

. I looked through the documentation and saw what the back

parameter takes key

, but I don't understand it and tried to put it in the screen name, for example back({ key: 'Screen B' })

, but it doesn't work, probably because it expects key

, which is randomly generated, unless specifically stated.

For example, I have this StackNavigator

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

      

Let's say I'm on now 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 this will add another screen to the stack, not what I expect.

+3


source to share


1 answer


1. Inside, screen D

send some action:

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

      

2.Set 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

+14


source







All Articles