【问题标题】:How to reset nested navigators (react-navigation v5)如何重置嵌套导航器(react-navigation v5)
【发布时间】:2020-12-06 02:11:29
【问题描述】:

拥有两组堆栈导航器;

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>
);

嵌套在抽屉导航器中

    <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'}]})

我应该如何处理resetnavigationCommonActions

【问题讨论】:

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


    【解决方案1】:

    正如 react-navigation-v5 的 documentation 中所写,您需要使用 reset-action 调度 CommonAction 以清除应用程序的后台堆栈,以便当用户按下硬件时应用程序不会返回上一屏幕设备的后退按钮,查看以下示例,

    import { CommonActions } from "@react-navigation/native";
    
    props.navigation.dispatch({
      ...CommonActions.reset({
        index: 0,
        routes: [{ name: "AnotherStackNavigator" }]
      })
    });
    

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

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

    【讨论】:

    • 在文档中很难找到您的解决方案!你拯救了我的一天......
    • 使用这个解决方案我面临一个问题。我可以导航到指定深度的不同堆栈,但后退按钮不会转到新堆栈的根目录。如何解决这个问题?
    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 2022-06-25
    • 2018-07-31
    • 1970-01-01
    • 2021-03-19
    • 2020-06-07
    • 1970-01-01
    • 2019-07-28
    相关资源
    最近更新 更多