React Navigation TabNavigator:在选项卡更改时重置上一个选项卡

IT技术 javascript reactjs react-native react-navigation
2021-04-24 06:00:43

我有以下路线结构:

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 而不是initialRoute1。

我正在做以下事情:

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.

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

3个回答

5.xx 版本的解决方案:

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

<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

版本 4.xx 的解决方案:

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

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

2.xx 和 3.xx 版本的解决方案:

问题是,当我重置路线时,我需要传递前一个 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
    }));
}

使用 unmountOnBlur 选项,它适用于所有类型的导航器、堆栈导航器、抽屉导航器、底部标签导航器

<Tab.Screen name="Home" component={DrawerNavigator} options={{unmountOnBlur:true}}/>

在导航器屏幕的选项props中传递 unmountOnBlur

您可以尝试使用这样的重置props:

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

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

编辑:如果这不能解决问题,您可以使用一些解决方法检查此 github 问题