React-native:返回堆栈中的特定屏幕

React-native: Go back to a specific screen in stack

这是根导航器

export const AppNavigator = StackNavigator({
        Splash: { screen: Splash },
        Dashboard: { screen: DashboardDrawer }
    });

const DashboardDrawer = DrawerNavigator({ DashboardScreen: {
        screen: StackNavigator({
            A: { screen: A },
            B: { screen: B },
            C: { screen: C },
            D: { screen: D },
        }
    }, {
        contentComponent: DashboardDrawerComponent,
        drawerWidth: 280
    });

我的堆栈中有 4 个屏幕 - A、B、C、D。 我想从 D 跳到 A。(或 D 到任何屏幕) 我参考了以下 react-navigation 文档-https://reactnavigation.org/docs/navigators/navigation-prop#goBack-Close-the-active-screen-and-move-back

以上文档。说明要从屏幕 D 转到屏幕 A(弹出 D、C 和 B),您需要提供一个返回键,在我的例子中是 B,就像这样

navigation.goBack(SCREEN_KEY_B)

所以,我的问题是 我应该从哪里获得特定屏幕的密钥? 我检查了我的根导航对象,它显示了一些为每个屏幕动态生成的键。 如何为屏幕指定我自己的键?

看起来他们现在的做法是通过 params 保存您要返回的屏幕的密钥。因此,一旦您进入 B 并导航到 C,您将屏幕密钥作为参数传递给 C,然后当您从 C 导航到 D 时,您将 B 的密钥作为参数传递给 D。

更多信息here

我使用 NavigatorService 的设置,如 unexge post 中概述的 here

从服务中,我公开了以下内容:

function goBackToRouteWithName(routeName: string) {
  if (!_container) return;
  const route = _getRouteWithName(_container.state.nav, routeName);
  route && _container.dispatch(NavigationActions.back({ key: route.key }));
}

function _getRouteWithName(route, name: string): ?NavigationRouteConfigMap {
  const stack = [];
  stack.push(route);
  while (stack.length > 0) {
    let current = stack.pop();
    if (current.routes) {
      for (let i = 0; i < current.routes.length; i++) {
        if (current.routes[i].routeName === name) {
          //NOTE because of going from, not to!!
          return current.routes[i + 1];
        }
        stack.push(current.routes[i]);
      }
    }
  }
}

这很适合我。

这很棘手!

我参考了这一段react-navigation的文档,实现了以上! https://reactnavigation.org/docs/routers/#Custom-Navigation-Actions

就是这样,

1. 稍微修改了问题中的 DrawerNavigator(以适应以下 stacknavigator)

const DrawerStackNavigator = new StackNavigator({
        A: { screen: A },
        B: { screen: B },
        C: { screen: C },
        D: { screen: D },
    }
});

const DashboardDrawer = DrawerNavigator({
        DashboardScreen: DrawerStackNavigator,
}, { 
       contentComponent: DashboardDrawerComponent,
       drawerWidth: 280
});

2. 在屏幕 D

中发送了一个动作
const {navigation} = this.props;
navigation.dispatch({
    routeName: 'A',
    type: 'GoToRoute',
});

3. 在我的堆栈导航器上收听了这个动作

const defaultGetStateForAction = DrawerStackNavigator.router.getStateForAction;
DrawerStackNavigator.router.getStateForAction = (action, state) => {            
    if (state && action.type === 'GoToRoute') {           
        let index = state.routes.findIndex((item) => {
            return item.routeName === action.routeName
        });
        const routes = state.routes.slice(0, index+1);
        return {
            routes,
            index
        };    
    }       
    return defaultGetStateForAction(action, state);
};