How to reset the state of a StackNavigator nested in a DrawerNavigatior?

試著忘記壹切 提交于 2020-01-02 03:34:06

问题


I am building an app whose navigation is based on a DrawerNavigator from the react-navigation library.

This navigator has 3 tabs:

  • 2 regular tabs
  • 1 StackNavigator named "Search"

The StackNavigator consists of one screen that lets the user search for an item, and a second screen where the user sees the search results.

I do not want the search results page to be a tab of a DrawerNavigator, this is why I implemented this structure.

The problem is: if the user has already performed a search, when he clicks on the "Search" tab, he does not come back to the search screen but to the search results screen. I would prefer that the user comes back to the search screen.

How can I achieve that?


回答1:


You can achive this using navigation dispatch with navigationActions

import { NavigationActions } from 'react-navigation';

const resetAction = NavigationActions.reset({
  index: 0,
  actions: [
    NavigationActions.navigate({
      routeName: 'DrawerScreen',
      params: {},
      action: NavigationActions.navigate({ routeName: 'SearchScreen' }),
    }),
  ],
})
navigation.dispatch(resetAction)



回答2:


import { NavigationActions } from 'react-navigation';

const resetAction = NavigationActions.reset({
  index: 0,
  actions: [
      NavigationActions.navigate({ routeName: 'SearchScreen'})
  ]
})

Here in your button or any element with event add this: this.props.navigation.dispatch(resetAction)

<Button
    onPress= {
        () => this.props.navigation.dispatch(resetAction)
    }
    title='Back to Search'
/>


来源:https://stackoverflow.com/questions/44654483/how-to-reset-the-state-of-a-stacknavigator-nested-in-a-drawernavigatior

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!