React Native 从导航堆栈中清除上一个屏幕

React Native clear the previous screen from the navigation stack

我正在开发一个用于学习目的的 React 本机应用程序。我现在正在使用 React Navigation 实现导航。我正在使用堆栈导航。但是我找不到从导航历史记录中删除上一个屏幕并终止该应用程序的方法。

我的导航是这样设置的。

const AppStack = createStackNavigator({
  Login: {
    screen: Login
  },
  Register: {
    screen: Register
  },
  Events: {
    screen: Events
  }
});

如您在上面的代码中看到的,我默认打开登录屏幕。登录后,我打开事件屏幕是这样的。

this.props.navigation.navigate('Events');

问题是,当我在活动页面上时,我可以在导航栏中看到后退按钮。当我按下它时,我被带回到登录页面。

但我想要的是,在登录后,我想从堆栈中删除登录页面。当我在活动页面上时,当我点击后退按钮时,应用程序应该关闭。也许它可能没有后退按钮。在这种情况下,它就像第一个屏幕一样。我该怎么做?

你需要的是重置功能

import {NavigationActions} from 'react-navigation';

this.props.navigation.dispatch(NavigationActions.reset({
     index: 0, key: null, actions: [NavigationActions.navigate({ routeName: 'Events' })]
 }));

成功完成登录或注册后,您必须像下面这样重置导航堆栈,

import { StackActions, NavigationActions } from 'react-navigation';
const resetAction = StackActions.reset({
    index: 0,
    actions: [NavigationActions.navigate({ routeName: 'Events' })],
});
this.props.navigation.dispatch(resetAction)

此外,如果您不希望 header 在您的 Event 页面中添加一个静态方法。

static navigationOptions = navigation => ({
        header: null
});

希望对您有所帮助。

import {StackActions, NavigationActions} from 'react-navigation';

this.props.navigation.dispatch(StackActions.reset({
     index: 0, key: null, actions: [NavigationActions.navigate({ routeName: 'Events' })]
 }));

从 V5 版本开始

this.props.navigation.reset({
        index: 0,
        routes: [{name: 'Events'}],
      });

在功能组件中使用钩子,

import {useNavigation} from '@react-navigation/native';

const navigation = useNavigation();

navigation.reset({
        index: 0,
        routes: [{name: 'Events'}],
      });

在V5.x中我们有reset方法

navigation.reset({
  index: 0,
  routes: [{ name: 'ScreenName' }],
});

2021 年更新:

这里有一个更简单的解决方案:

this.props.navigation.replace("Events");

这将用新屏幕替换当前屏幕,同时在导航堆栈中保留任何以前的屏幕。

深思

理想情况下,您会使用最佳实践并执行以下操作:

import * as ROUTES from "../routes/constants"

this.props.navigation.replace(ROUTES.EVENTS);

其中 routes/constants.js,

const EVENTS = "Events";
...

export {
    EVENTS,
    ...
};