React Navigation TabNavigator: Reset previous tab when changing tabs

I have the following route structure:

StackNavigator
-StackNavigator
-TabNavigator
--Tab1
---Route 1 (Stack) (initial)
---Route 2 (Stack)

--Tab2
---Route 3 (Stack) (initial)
---Route 4 (Stack)

When I find Tab1 -> Route 1 -> Route 2 -> Tab2and get back to Tab1, the active route is 2 instead of initialRoute1.

I do the following:

tabBarOnPress: ({ scene }) => {
    const { route } = scene;
    const tabRoute = route.routeName;
    const { routeName } = route.routes[0];

    navigation.dispatch(NavigationActions.navigate({ routeName: tabRoute }));

    navigation.dispatch(NavigationActions.reset({
        index: 0,
        actions: [
            NavigationActions.navigate({ routeName }),
        ],
    }));
},

but the problem is that it shows first Route 2, and then go to Route 1.

How can I use reset previous tabs / screens, so when I switch the tab always, to show the initial route directly.

+4
source share
2 answers

The problem is that when I reset the route, I need to pass the navigation action of the previous route Name (leave the tab) and send a new navigation action for the following route:

tabBarOnPress: ({ previousScene, scene }) => {
    const tabRoute = scene.route.routeName;
    const prevRouteName = previousScene.routes[0].routeName;

    navigation.dispatch(NavigationActions.reset({
        index: 0,
        actions: [
            NavigationActions.navigate({
                routeName: prevRouteName
            }),
        ],
    }));

    navigation.dispatch(NavigationActions.navigate({
        routeName: tabRoute
    }));
}
+2

reset :

tabBarOnPress: ({ scene }) => {
    const { route } = scene;
    const tabRoute = route.routeName;
    const { routeName } = route.routes[0];

    navigation.dispatch(NavigationActions.reset({
        index: 1,
        actions: [
            NavigationActions.navigate({ routeName }),
            NavigationActions.navigate({ routeName: tabRoute })
        ],
    }));
},

: , github

0

Source: https://habr.com/ru/post/1692760/


All Articles