我有以下路由 struct :

StackNavigator
-StackNavigator
-TabNavigator
--Tab1
---Route 1 (Stack) (initial)
---Route 2 (Stack)

--Tab2
---Route 3 (Stack) (initial)
---Route 4 (Stack)

当我访问Tab1 -> Route 1 -> Route 2 -> Tab2并返回Tab1时,活动路由是2,而不是initialRoute 1.

我正在做以下工作:

tabBarOnPress: ({ scene }) => {
    const { route } = scene;
    const tabRoute = route.routeName;
    const { routeName } = route.routes[0];

    navigation.dispatch(NavigationActions.navigate({ routeName: tabRoute }));

    navigation.dispatch(NavigationActions.reset({
        index: 0,
        actions: [
            NavigationActions.navigate({ routeName }),
        ],
    }));
},

但问题是,它首先显示Route 2,然后导航到Route 1.

如何重置之前的选项卡/屏幕,以便在切换选项卡时始终直接显示初始路由.

推荐答案

Solution for version 5.x.x:

将侦听器传递到屏幕组件:

<Tab.Screen
     name="homeTab"
     component={HomeStackScreen}
     listeners={tabBarListeners}
/>

然后,在该侦听器上,每当用户按下选项卡时,导航用户:

const tabBarListeners = ({ navigation, route }) => ({
    tabPress: () => navigation.navigate(route.name),
});

学分:https://github.com/react-navigation/react-navigation/issues/8583

Solution for version 4.x.x:

tabBarOnPress: ({ navigation }) => {
  navigation.popToTop();
  navigation.navigate(navigation.state.routeName);
}

学分:https://github.com/react-navigation/react-navigation/issues/1557

Solution for versions 2.x.x and 3.x.x:

问题是,当我重置路由时,我需要通过上一个routeName(离开选项卡)的导航操作,并为下一条路由分配新的导航操作:

tabBarOnPress: ({ previousScene, scene }) => {
    const tabRoute = scene.route.routeName;
    const prevRouteName = previousScene.routes[0].routeName;

    navigation.dispatch(NavigationActions.reset({
        index: 0,
        actions: [
            NavigationActions.navigate({
                routeName: prevRouteName
            }),
        ],
    }));

    navigation.dispatch(NavigationActions.navigate({
        routeName: tabRoute
    }));
}

React-native相关问答推荐

react 本机中的TextInput对齐中的长文本

防止 React Native 在上下文值更改时重新安装组件

React Native Ios错误 - ENOENT:no such file or directory, uv_cwd (null)

Javascript setTimeout 立即在 React Native 中运行

React Native - 初始属性 Android

如何更改 React Native(android)应用程序的远程推送通知图标

由于依赖关系,在 run-android 上构建失败

中彼此相邻对齐(Align) react native

缺少请求的请求令牌

这个 refs 在方法中变得未定义

如何将组件中的props传递给 FlatList renderItem

带有 react-navigation 的 DrawerNavigation 标头

如何在react native应用程序名称中添加空格?

FlatList contentContainerStyle -> justifyContent: 'center' 导致滚动问题

如何在 array.map 中的每个元素之后添加逗号,除了 React JSX 中的最后一个元素

可以react native使用jQuery

react-native Http 拦截器

react-native Bottom Up drawer

如何使用特定目标运行 react-native run-ios

在 React Native Navigator 中的组件之间传递值