如何重置嵌套导航器(react-navigation v5)

时间:2020-08-16 22:14:57

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

具有两组堆栈导航器;

const SetOneScreens = () => (
  <Stack.Navigator initialRouteName="AScreen">
    <Stack.Screen name="AScreen" component={AScreen} />
    <Stack.Screen name="BScreen" component={BScreen} />
  </Stack.Navigator>
);
const SetTwoScreens = () => (
  <Stack.Navigator initialRouteName="CScreen">
    <Stack.Screen name="CScreen" component={CScreen} />
    <Stack.Screen name="DScreen" component={DScreen} />
  </Stack.Navigator>
);

哪个嵌套在Drawer导航器中

    <NavigationContainer>
      <Drawer.Navigator initialRouteName="SetOneScreens">
        <Drawer.Screen name="SetOneScreens" component={SetOneScreens} />
        <Drawer.Screen name="SetTwoScreens" component={SetTwoScreens} options={{swipeEnabled: false}} />
      </Drawer.Navigator>
    </NavigationContainer>

我想从BScreen导航到DScreen并重置堆栈(为了不让android中的硬件后退按钮回到BScreen

与嵌套情况一样,我们应该首先定义导航器名称;我该如何在重置操作中定义屏幕。

// For navigation 
props.navigation.navigate('setTwoScreens',{screen:'DScreen'})

// For reset I can only navigate to initial screen 
props.navigation.reset({index:0,routes:[{name:'setTwoScreens'}]})

我应该如何用resetnavigation处理CommonActions

1 个答案:

答案 0 :(得分:5)

如react-navigation-v5的documentation所述,您需要使用reset-action调度CommonAction来清除应用程序的后向堆栈,这样当用户使用时,应用程序不会返回到上一个屏幕按下设备的硬件后退按钮,检查以下示例,

204

或者,如果您想在该StackNavigator中重置为特定的屏幕,您可以这样做:

import { CommonActions } from "@react-navigation/native";

props.navigation.dispatch({
  ...CommonActions.reset({
    index: 0,
    routes: [{ name: "AnotherStackNavigator" }]
  })
});