【问题标题】:How do i keep initial route with nested navigation with React Navigation v5?如何使用 React Navigation v5 使用嵌套导航保持初始路线?
【发布时间】:2021-01-21 00:33:04
【问题描述】:

首先让我声明我知道如何使用反应导航从一个嵌套页面导航到另一个嵌套页面。但是,每当我导航到不是初始路由的嵌套屏幕时,每当我导航回该嵌套堆栈时,该屏幕现在就会成为第一个屏幕。

示例

  • 父导航器
    • 嵌套堆栈导航器 1
      • 屏幕 A(初始路线)
      • 屏幕 B
    • 嵌套堆栈导航器 2
      • 屏幕 C(初始路线)
      • 屏幕 D
    • 嵌套堆栈导航器 2
      • 屏幕 E(初始路线)
      • 屏幕 F

通常当从一个堆栈导航到Nested Stack Navigator 2 时,我使用以下内容。

navigation.navigate('Nested Navigator 2');

这将我带到screen C,这是预期的行为。但是,每当我从另一个堆栈导航到screen D 时,我注意到每当我使用上面的代码导航回Nested Stack Navigator 2 时,它不再打开screen C,而是打开screen D

这就是我从另一个堆栈导航到screen D 的方式。

navigation.navigate('Nested Navigator 2', { screen: 'screen D', initial: false });

每当使用 screen D 作为初始路线时,事件虽然我在导航调用中指定了 initial: false。有没有办法防止这种情况发生?

【问题讨论】:

    标签: react-native react-navigation react-navigation-stack


    【解决方案1】:

    一旦您导航到嵌套堆栈导航的初始路由组件以外的另一个组件,navigation.navigate('Nested Navigator 2'); 将不起作用

    初始您的导航堆栈将在初始路线上显示此内容

    [
     { name: ScreenA },
     { name: ScreenC },
     { name: ScreenE }
    ]
    

    但是每当你从sreen C导航到Screen D时,Screen D的路由不会插入到栈的末尾,因为它是嵌套导航二

    [
     { name: ScreenA },
     { 
       name: NestedNavigator,
       [
        { name: screenC }, 
        { name: screenD }
       ]
     },
     { name: ScreenE }
    ]
    

    所以你需要使用, navigation.navigate('嵌套导航器 2', { screen: 'screen D' }); 这是因为当您导航到初始路线以外的屏幕时,堆栈会发生变化,

    您需要在嵌套组件上重置路由,即每当您导航到屏幕 D 时,使用 commonActions 重置路由堆栈,设置屏幕,这将更新堆栈,并从堆栈中删除屏幕 D。

    import { CommonActions } from '@react-navigation/native';
    
    componentDidMount() {
       this.props.navigation.addListener('blur', () => {
                this.props.navigation.dispatch(
                    CommonActions.reset({
                      index: 1,
                      routes: [
                        { name: 'ScreenC' },
                        
                      ],
                    })
                  );
            });
        }
    

    如果您只想删除某条路线而不是重置整个导航

     this.props.navigation.dispatch(state => {
                // Remove the route from the stack
                const routes = state.routes.filter((r => r.name !== 'ScreenC' ));
            
                return CommonActions.reset({
                  ...state,
                  routes,
                  index: routes.length - 1,
                });
              });
    

    【讨论】:

    • 谢谢你是对的,它确实覆盖了默认导航状态。我所做的修复是始终指定我要去的屏幕,因为初始路线不再起作用。
    猜你喜欢
    • 2020-12-06
    • 2021-12-23
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2022-06-25
    相关资源
    最近更新 更多