gpt4 book ai didi

android - 防止用户返回到上一屏幕 StackNavigator

转载 作者:行者123 更新时间:2023-12-03 13:40:17 28 4
gpt4 key购买 nike

我想做一个简单的任务:成功登录后将用户重定向到他的主页。我使用react-navigation的StackNavigator来达到这个目的:

// App.js

class App extends Component {
render() {
return (<RootStack />);
}
}

const RootStack = createStackNavigator(
{
Login: { screen: Login, navigationOptions: { header: null }},
Home: { screen: Home, navigationOptions: { header: null }}
},
{
initialRouteName: 'Root'
}
)

如何防止用户在登录后返回登录屏幕?为了防止在 android 中使用后退按钮,我会使用这个:

// Home.js

import React, { Component} from 'react';
import { ... , BackHandler } from 'react-native';

class Home extends Component {
constructor(props) {
super(props);
BackHandler.addEventListener('hardwareBackPress', this.onBackButtonPressAndroid);
}
onBackButtonPressAndroid = () => {
return true;
}
}

但是这样做,我完全禁用了后退按钮。还有其他方法可以实现目标吗?

最佳答案

react native documentation有一个关于如何进行身份验证流程的优秀页面。

You may not be familiar with SwitchNavigator yet. The purpose of SwitchNavigator is to only ever show one screen at a time. By default, it does not handle back actions and it resets routes to their default state when you switch away. This is the exact behavior that we want from the authentication flow: when users sign in, we want to throw away the state of the authentication flow and unmount all of the screens, and when we press the hardware back button we expect to not be able to go back to the authentication flow. We switch between routes in the SwitchNavigator by using the navigate action. You can read more about the SwitchNavigator in the API reference.

根据文档,这个SwitchNavigator是这样实现的:

import { createSwitchNavigator, createStackNavigator } from 'react-navigation';

// Implementation of HomeScreen, OtherScreen, SignInScreen, AuthLoadingScreen
// goes here.

const AppStack = createStackNavigator({ Home: HomeScreen, Other: OtherScreen });
const AuthStack = createStackNavigator({ SignIn: SignInScreen });

export default createSwitchNavigator(
{
AuthLoading: AuthLoadingScreen,
App: AppStack,
Auth: AuthStack,
},
{
initialRouteName: 'AuthLoading',
}
);

因此,为了实现您正在寻找的目标,您需要将您的 RootStack 更改为以下内容(请注意,我尚未测试此代码):

const RootStack = createSwitchNavigator(
{
Loading: ,//put your loading screen here
Auth: { screen: Login, navigationOptions: { header: null }},
App: { screen: Home, navigationOptions: { header: null }}
},
{
initialRouteName: 'Loading'
}
)

然后,在加载屏幕中,您将获取确定用户是否已登录所需的任何状态,并且您将调用 this.props.navigation.navigate('App'); 跳过登录屏幕并将用户直接带到您的应用,或 this.props.navigation.navigate('Auth'); 将您的用户发送到登录页面。 SwitchNavigator 自动为您处理禁用后退导航的操作。

关于android - 防止用户返回到上一屏幕 StackNavigator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50932871/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com