Disable back button in react navigation

前端 未结 18 1714
长发绾君心
长发绾君心 2020-12-12 18:31

I\'m using react native navigation (react-navigation) StackNavigator. it starts from the Login page throughout the whole lifecycle of the app. I don\'t want to have a back

18条回答
  •  不思量自难忘°
    2020-12-12 19:18

    The best option to handle this situation is to use SwitchNavigator provided by React navigation. 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 is needed in the authentication flow.

    This is a typical way to implement it.

    1. Create 2 stack navigators: One for authentication (sign in, sign up, forgot password, etc) and another for the main APP
    2. Create a screen in which you will check which route from switch navigator you want to show (I usually check this in splash screen by checking if a token is stored in Async storage)

    Here is a code implementation of above statements

    import { createAppContainer, createSwitchNavigator } from 'react-navigation';
    import { createStackNavigator } from 'react-navigation-stack';
    import HomeScreen from "./homeScreenPath" 
    import OtherScreen from "./otherScreenPath"
    import SignInScreen from "./SignInScreenPath" 
    import SplashScreen from "./SplashScreenPath"
    
    const AppStack = createStackNavigator({ Home: HomeScreen, Other: OtherScreen });
    
    const AuthStack = createStackNavigator({ SignIn: SignInScreen });
    
    
    export default createAppContainer(
      createSwitchNavigator(
        {
          Splash: SplashScreen,
          App: AppStack,
          Auth: AuthStack,
        },
        {
          initialRouteName: 'Splash',
        }
      )
    );

    Now in SplashScreen you will check the token and navigate accordingly

    import React from 'react';
    import {
      ActivityIndicator,
      AsyncStorage,
      StatusBar,
      StyleSheet,
      View,
    } from 'react-native';
    
    class SplashScreen extends React.Component {
      componentDidMount() {
        this.checkIfLogin();
      }
    
      // Fetch the token from storage then navigate to our appropriate place
      checkIfLogin = async () => {
        const userToken = await AsyncStorage.getItem('userToken');
    
        // This will switch to the App screen or Auth screen and this splash
        // screen will be unmounted and thrown away.
        this.props.navigation.navigate(userToken ? 'App' : 'Auth');
      };
    
      // Render any loading content that you like here
      render() {
        return (
          
            
            
          
        );
      }
    }

    Once you change routes in SwitchNavigator it removes the older route automatically and hence if you press the back button it will not take you to the auth/login screens anymore

提交回复
热议问题