1
votes

Context: building a React Native mobile application. Along the bottom of the UI are four tabs. Three contain simple StackNavigators to preserve navigation state within that tab. The fourth screen is itself a tab navigator. The screen of each sub-tab is a StackNavigator to preserve their own navigation history while within the tab.

Outline:

The top level navigator:

BottomTabNavigator
|_Tab 1 (StackNavigator) (initial route)
|_Tab 2 (StackNavigator)
|_Tab 3 (StackNavigator)
|_Tab 4 (Tab4Container)

The sub-navigator:

Tab4Navigator (MaterialTopTabNavigator)
  |_Subtab 1 (StackNavigator) (initial route)
    |_Screen 4.1.1 (initial route)
    |_Screen 4.1.2
  |_Subtab 2 (StackNavigator) (initial route)
    |_Screen 4.2.1 (initial route)
    |_Screen 4.2.2

Tab 4 has a few components above the tabs themselves, so that's wrapped in a container. Essentially:

class Tab4Container extends React.router {
  render() {
    return(
      <View>
        <Header />
        <Tab4Navigator navigation={this.props.navigation}>
      </View>
    )
  }
}

Issue: The nested tab navigator doesn't reset its state when the user leaves Tab4 and comes back. First, the user clicks to Tab4, then Subtab 2, then Screen 4.2.2. Then the user clicks on Tab 2. Then the user returns to Tab 4. The current screen should be 4.1.1 but it is still 4.2.2.

Tab4Navigator is structured:

const Tab4Navigator = createMaterialTopTabNavigator(
  {
    subTab1: createStackNavigator(
      {
        screen_4_1_1: {
          screen: Screen411Container
        },
        screen_4_1_2: {
          screen: Screen412Container
        },
      },
      { initialRouteName: "screen_4_2_1" }
    ),
    subTab2: createStackNavigator(
      {
        screen_4_2_1: {
          screen: Screen421Container
        },
        screen_4_2_2: {
          screen: Screen422Container
        },
      },
      { initialRouteName: "screen_4_2_1" }
    ),
  },
  { initialRouteName: "subTab1" }
)

Question: How can I reset the StackNavigator when the Tab4Navigator is re-rendered?

1
This is how stacknavigator works and it keeps the state of the stack until you reset it. - prabhat
@prabhat Yes that's the case. I'm asking how to reset the state when the tab is re-rendered. I'll add that explicitly to the question - Chris

1 Answers

2
votes

You have to add tabBarOnPress event on Tab4Navigator and then reset stack . Check this GitHub link also

import { StackActions, NavigationActions } from 'react-navigation';

......

{ initialRouteName: "subTab1", tabBarOnPress: this.handleTabPress }

handleTabPress = ({ navigation }) => {
  navigation.popToTop();
  navigation.navigate(navigation.state.routeName);
}