Have a stack navigator always render initialRoute

放肆的年华 提交于 2020-07-10 10:18:27

问题


I'm building a react native app and I'm using react-navigation package. I have a tab navigator for the app and each tab has a stack navigator in it. Something like this:

const HomeStack = StackNavigation({
    Info: {screen: Info},
    Main: {screen: Main}
})

const SearchStack = StackNavigation({
    Search: {screen: Search},
    SearchResult: {screen: SearchResult}
})

TabNavigation({
  Home: {screen: HomeStack},
  Search: {screen: SearchStack}
})

So let's say I did a search and I'm now on SearchResult screen. I then go back to Home screen by pressing home tab. Now when I go back to search tab it shows me the SearchResult screen. Is there a way to force react-navigation to always render a Search screen when you go to it from the Tab?

I made a project on snack to illustrate this https://snack.expo.io/rkMzWoh17


回答1:


use initial route name like this in searchstack navigation like this

 {
    initialRouteName: 'Search',
  }



回答2:


You can use something like this inside every stack screen.

   const Search = ({ navigation }) => {
      useLayoutEffect(() => {
          const blur = navigation.addListener('blur', () => {
            navigation.popToTop();
          });
      }, []);
   }

This pops the stack to the initial screen everytime you navigate away.

More information here: https://reactnavigation.org/docs/navigation-events



来源:https://stackoverflow.com/questions/50614025/have-a-stack-navigator-always-render-initialroute

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