卸载所有先前安装的屏幕以在后退时退出应用程序

Unmount all previously mounted screens to exit the app on back press

我有一个要求,我需要在按下后退按钮时退出应用程序。基本上,我尝试使用 BackHandler API,它有效但有一定的局限性。因此,就我而言,我觉得最好的方法是卸载所有以前安装的组件,以便当前屏幕成为堆栈中的第一个屏幕。

我有以下屏幕:

登录
OtpVerification
姓名
电子邮件
. . .还有更多

我需要的是,当我在 Name 屏幕上时,如果有人按下后退按钮,应用程序应该退出。但是如果有人在 Email 屏幕上,用户应该只能返回到 Name 屏幕。

使用 BackHandler 的代码段

constructor(props) {
    super(props);
    .
    .
    BackHandler.addEventListener("hardwareBackPress", this._handleBackPress);
}
.
.
.
.
_handleBackPress = () => {
    BackHandler.exitApp();
};
.
.
.
.
_onPress = () => {
    BackHandler.removeEventListener("hardwareBackPress", this._handleBackPress);
    this.props.navigation.navigate("Email", { name: this.state.name });
};

此问题的解决方案是在导航到“名称”屏幕之前重置堆栈导航器。

在 react-navigation 中使用 reset 操作来执行此操作。 documentation

执行此操作的函数的一个简单示例是 -

反应导航 5 - 使用 CommonActions

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

reset = (routeName) => {
  return navigation.dispatch(
    CommonActions.reset({
      index: 0,
      routes: [{ name: routeName }],
    })
  );
};

反应导航v4.x

reset = (routeName) => {
  return this.props.navigation.dispatch(
    NavigationActions.reset({
      index: 0,
      actions: [NavigationActions.navigate({ routeName })],
    })
  );
};

将其放入 OtpVerification 屏幕并在导航到 NameScreen

时调用 reset('NameScreen')

相关回答 -