How to reset TabNavigator when user logs out (from other screen)

后端 未结 3 1151
心在旅途
心在旅途 2020-11-27 19:49

Here is my project file hierarchy

RootTabNavigator
    | AuthStackNavigator // I want to go back to this navigator
          | AuthoScreen
    | Welcome Scre         


        
3条回答
  •  一向
    一向 (楼主)
    2020-11-27 20:18

    What you need is to initialize the navigator to the initial state. You can do that with NavigationActions.init(). You can learn more about Navigations Actions here.

    You can do this by creating a Custom Navigation Action, read more about them here.

    Here's some code that would do that for you:

    // First get a hold of your navigator
    const navigator = ...
    
    // Get the original handler
    const defaultGetStateForAction = navigator.router.getStateForAction
    
    // Then hook into the router handler
    navigator.router.getStateForAction = (action, state) => {
    
      if (action.type === 'MyCompleteReset') {
         // For your custom action, reset it all
         return defaultGetStateForAction(NavigationActions.init())
      }
    
      // Handle all other actions with the default handler
      return defaultGetStateForAction(action, state)
    }
    

    In order to trigger your Custom Navigation Action, you have to dispatch it as follows from within your React Component:

      this.props.navigation.dispatch({
          type: "MyCompleteReset",
          index: 0
        })
    

提交回复
热议问题