Home Web Front-end JS Tutorial How to determine whether the user is logged in and jump to the login page in react-navigation

How to determine whether the user is logged in and jump to the login page in react-navigation

Jun 23, 2018 pm 02:24 PM
react Log in

This article mainly introduces how react-navigation determines whether the user is logged in and jumps to the login page. It has certain reference value. Interested friends can refer to it.

This article introduces react -navigation How to determine whether the user is logged in and jump to the login page? Share it with everyone and leave a note for yourself. The details are as follows:

Create a new index.js

import React, {Component} from 'react'; 
import {AppRegistry, Text, View, Button,Image,StyleSheet,BackHandler,ToastAndroid} from 'react-native'; 
import { StackNavigator,TabNavigator,NavigationActions } from 'react-navigation'; 
 
 
 
//全局存储 
import stroage from './StorageUtil'; 
import './Global' 
 
import IndexScreen from './Index' 
import MeScreen from './Me' 
import Login from './Login' 
 
 
//底部菜单栏设置 
const MainScreenNavigator = TabNavigator({ 
    IndexScreen: { 
      screen: IndexScreen, 
      navigationOptions: { 
        tabBarLabel: '首页', 
        headerLeft:null,//去除返回按钮 
        tabBarIcon: ({ tintColor }) => ( 
          <Image 
            source={require(&#39;./img/ic_image.png&#39;)} 
            style={[styles.icon, {tintColor: tintColor}]} 
          /> 
        ), 
        onNavigationStateChange:(()=> alert("首页")) 
        // initialRouteName:&#39;IndexScreen&#39; 
      }, 
    }, 
     
    MeScreen: { 
      screen: MeScreen, 
      navigationOptions: { 
        tabBarLabel:&#39;我的&#39;, 
        tabBarIcon: ({ tintColor }) => ( 
          <Image 
            source={require(&#39;./img/ic_me.png&#39;)} 
            style={[styles.icon, {tintColor: tintColor}]} 
          /> 
        ), 
        // initialRouteName:&#39;MeScreen&#39; 
      } 
    } 
  }, 
  { 
    // trueinitialRouteName:&#39;MeScreen&#39;,//设置默认的页面组件 
    // initialRouteName:&#39;MeScreen&#39;, 
    lazy:true,//是否根据需要懒惰呈现标签,而不是提前,意思是在app打开的时候将底部标签栏全部加载,默认false,推荐为true 
    // order: [&#39;IndexScreen&#39;,&#39;FindScreen&#39;,&#39;ListNewScreen&#39;,&#39;MeScreen&#39;], //order 来定义tab显示的顺序,数组形式 
    animationEnabled: false, // 切换页面时是否有动画效果 
    tabBarPosition: &#39;bottom&#39;, // 显示在底端,android 默认是显示在页面顶端的 
    swipeEnabled: false, // 是否可以左右滑动切换tab 
    // backBehavior: &#39;none&#39;, // 按 back 键是否跳转到第一个Tab(首页), none 为不跳转 
    tabBarOptions: { 
      activeTintColor: &#39;#2196f3&#39;, // 文字和图片选中颜色 
      inactiveTintColor: &#39;#999&#39;, // 文字和图片未选中颜色 
      showIcon: true, // android 默认不显示 icon, 需要设置为 true 才会显示 
      indicatorStyle: { 
        height: 0 // 如TabBar下面显示有一条线,可以设高度为0后隐藏 
      }, 
      style: { 
        backgroundColor: &#39;#fff&#39;, // TabBar 背景色 
        height: 60 
      }, 
      labelStyle: { 
        fontSize: 14, // 文字大小 
        marginTop:2 
        // lineHeight:44 
      }, 
    } 
  }); 
 
//跳转路由设置 
const FirstApp = StackNavigator({ 
  IndexScreen: { 
    screen: MainScreenNavigator, 
    // initialRouteName: &#39;IndexScreen&#39; 
  }, 
  MeScreen: {screen: MeScreen}, 
  Login:{screen: Login}, 
   
}, { 
  initialRouteName: &#39;IndexScreen&#39;, // 默认显示界面 
  navigationOptions: { // 屏幕导航的默认选项, 也可以在组件内用 static navigationOptions 设置(会覆盖此处的设置) 
    headerStyle:{elevation: 0,shadowOpacity: 0,height:48,backgroundColor:"#2196f3"}, 
    headerTitleStyle:{color:&#39;#fff&#39;,fontSize:16}, //alignSelf:&#39;center&#39; 文字居中 
    headerBackTitleStyle:{color:&#39;#fff&#39;,fontSize:12}, 
    // headerTintColor:{}, 
    gesturesEnabled:true,//是否支持滑动返回收拾,iOS默认支持,安卓默认关闭 
  }, 
  mode: &#39;card&#39;, // 页面切换模式, 左右是card(相当于iOS中的push效果), 上下是modal(相当于iOS中的modal效果) 
  headerMode: &#39;screen&#39;, // 导航栏的显示模式, screen: 有渐变透明效果, float: 无透明效果, none: 隐藏导航栏 
  onTransitionStart: (Start)=>{console.log(&#39;导航栏切换开始&#39;);}, // 回调 
  onTransitionEnd: ()=>{ console.log(&#39;导航栏切换结束&#39;); } // 回调 
}); 
// 
const defaultGetStateForAction = FirstApp.router.getStateForAction; 
 
FirstApp.router.getStateForAction = (action, state) => { 
  //页面是MeScreen并且 global.user.loginState = false || &#39;&#39;(未登录) 
  if (action.routeName ===&#39;MeScreen&#39;&& !global.user.loginState) { 
    this.routes = [ 
      ...state.routes, 
      {key: &#39;id-&#39;+Date.now(), routeName: &#39;Login&#39;, params: { name: &#39;name1&#39;}}, 
    ]; 
    return { 
      ...state, 
      routes, 
      index: this.routes.length - 1, 
    }; 
  } 
  return defaultGetStateForAction(action, state); 
}; 
 
 
export default class FirstAppDemo extends Component { 
  render() { 
    return ( 
      <FirstApp /> 
    ); 
  } 
} 
 
AppRegistry.registerComponent(&#39;FirstApp&#39;, () => FirstAppDemo); 
 
 
const styles = StyleSheet.create({ 
  icon: { 
    width: 26, 
    height: 26, 
  }, 
});
Copy after login

Create a global Storage StorageUtil.js

import React, {Component} from &#39;react&#39;; 
import {AsyncStorage} from &#39;react-native&#39;; 
import Storage from &#39;react-native-storage&#39;; 
 
var storage = new Storage({ 
  // 最大容量,默认值1000条数据循环存储 
  size: 1000, 
 
  // 存储引擎:对于RN使用AsyncStorage,对于web使用window.localStorage 
  // 如果不指定则数据只会保存在内存中,重启后即丢失 
  storageBackend: AsyncStorage, 
 
  // 数据过期时间,默认一整天(1000 * 3600 * 24 毫秒),设为null则永不过期 
  defaultExpires: 1000 * 3600 * 24, 
 
  // 读写时在内存中缓存数据。默认启用。 
  enableCache: true, 
 
  // 如果storage中没有相应数据,或数据已过期, 
  // 则会调用相应的sync方法,无缝返回最新数据。 
  // sync方法的具体说明会在后文提到 
  // 你可以在构造函数这里就写好sync的方法 
  // 或是写到另一个文件里,这里require引入 
  // 或是在任何时候,直接对storage.sync进行赋值修改 
  //sync: require(&#39;./sync&#39;) // 这个sync文件是要你自己写的 
}) 
 
// 最好在全局范围内创建一个(且只有一个)storage实例,方便直接调用 
 
// 对于web 
// window.storage = storage; 
 
// 对于react native 
// global.storage = storage; 
 
// 这样,在此**之后**的任意位置即可以直接调用storage 
// 注意:全局变量一定是先声明,后使用 
// 如果你在某处调用storage报错未定义 
// 请检查global.storage = storage语句是否确实已经执行过了 
 
//导出为全局变量 
global.storage = storage; 

新建一个全局变量组件Global.js,用户存储用户登录的信息
 
//用户登录数据 
global.user = { 
  loginState:&#39;&#39;,//登录状态 
  userData:&#39;&#39;,//用户数据 
}; 
//刷新的时候重新获得用户数据  
storage.load({ 
  key: &#39;loginState&#39;, 
}).then(ret => { 
  global.user.loginState = true; 
  global.user.userData = ret; 
}).catch(err => { 
  global.user.loginState = false; 
  global.user.userData = &#39;&#39;; 
})
Copy after login

Login component Login.js

_login() {//登录函数 
    // debugger; 
    ToastUtil.show("登录成功"); 
    // 使用key来保存数据。这些数据一般是全局独有的,常常需要调用的。 
    // 除非你手动移除,这些数据会被永久保存,而且默认不会过期。 
    storage.save({ 
      key: &#39;loginState&#39;, // 注意:请不要在key中使用_下划线符号! 
      data: { 
        userid: &#39;1001&#39;, 
        userName:&#39;userName&#39;, 
        token: &#39;token&#39; 
      }, 
 
      // 如果不指定过期时间,则会使用defaultExpires参数 
      // 如果设为null,则永不过期 
      // 8个小时后过期 
      expires: 1000 * 3600 * 8 
    }); 
    global.user.loginState = true;//设置登录状态 
    global.user.userData = { userid: &#39;1001&#39;, userName:&#39;userName&#39;, token: &#39;token&#39;};//保存用户数据 
 
    setTimeout(()=>{ 
      this.props.navigation.navigate(&#39;UserScreen&#39;)//跳转到用户页面 
    },2000) 
     
  }
Copy after login

The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.

Related articles:

Detailed interpretation of the navigation usage of react-navigation

Detailed interpretation of Function function in javascript (detailed tutorial)

How to implement custom visualization using AngularJS2 integrated with D3.js

How to implement sequential loading and running js methods in javascript

The above is the detailed content of How to determine whether the user is logged in and jump to the login page in react-navigation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? What should I do if I download other people's wallpapers after logging into another account on wallpaperengine? Mar 19, 2024 pm 02:00 PM

When you log in to someone else's steam account on your computer, and that other person's account happens to have wallpaper software, steam will automatically download the wallpapers subscribed to the other person's account after switching back to your own account. Users can solve this problem by turning off steam cloud synchronization. What to do if wallpaperengine downloads other people's wallpapers after logging into another account 1. Log in to your own steam account, find cloud synchronization in settings, and turn off steam cloud synchronization. 2. Log in to someone else's Steam account you logged in before, open the Wallpaper Creative Workshop, find the subscription content, and then cancel all subscriptions. (In case you cannot find the wallpaper in the future, you can collect it first and then cancel the subscription) 3. Switch back to your own steam

How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? How do I log in to my previous account on Xiaohongshu? What should I do if the original number is lost after it is reconnected? Mar 21, 2024 pm 09:41 PM

With the rapid development of social media, Xiaohongshu has become a popular platform for many young people to share their lives and explore new products. During use, sometimes users may encounter difficulties logging into previous accounts. This article will discuss in detail how to solve the problem of logging into the old account on Xiaohongshu, and how to deal with the possibility of losing the original account after changing the binding. 1. How to log in to Xiaohongshu’s previous account? 1. Retrieve password and log in. If you do not log in to Xiaohongshu for a long time, your account may be recycled by the system. In order to restore access rights, you can try to log in to your account again by retrieving your password. The operation steps are as follows: (1) Open the Xiaohongshu App or official website and click the &quot;Login&quot; button. (2) Select &quot;Retrieve Password&quot;. (3) Enter the mobile phone number you used when registering your account

Discuz background login problem solution revealed Discuz background login problem solution revealed Mar 03, 2024 am 08:57 AM

The solution to the Discuz background login problem is revealed. Specific code examples are needed. With the rapid development of the Internet, website construction has become more and more common, and Discuz, as a commonly used forum website building system, has been favored by many webmasters. However, precisely because of its powerful functions, sometimes we encounter some problems when using Discuz, such as background login problems. Today, we will reveal the solution to the Discuz background login problem and provide specific code examples. We hope to help those in need.

How to log in to Kuaishou PC version - How to log in to Kuaishou PC version How to log in to Kuaishou PC version - How to log in to Kuaishou PC version Mar 04, 2024 pm 03:30 PM

Recently, some friends have asked me how to log in to the Kuaishou computer version. Here is the login method for the Kuaishou computer version. Friends who need it can come and learn more. Step 1: First, search Kuaishou official website on Baidu on your computer’s browser. Step 2: Select the first item in the search results list. Step 3: After entering the main page of Kuaishou official website, click on the video option. Step 4: Click on the user avatar in the upper right corner. Step 5: Click the QR code to log in in the pop-up login menu. Step 6: Then open Kuaishou on your phone and click on the icon in the upper left corner. Step 7: Click on the QR code logo. Step 8: After clicking the scan icon in the upper right corner of the My QR code interface, scan the QR code on your computer. Step 9: Finally log in to the computer version of Kuaishou

How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance How to enter Baidu Netdisk web version? Baidu Netdisk web version login entrance Mar 13, 2024 pm 04:58 PM

Baidu Netdisk can not only store various software resources, but also share them with others. It supports multi-terminal synchronization. If your computer does not have a client downloaded, you can choose to enter the web version. So how to log in to Baidu Netdisk web version? Let’s take a look at the detailed introduction. Baidu Netdisk web version login entrance: https://pan.baidu.com (copy the link to open in the browser) Software introduction 1. Sharing Provides file sharing function, users can organize files and share them with friends in need. 2. Cloud: It does not take up too much memory. Most files are saved in the cloud, effectively saving computer space. 3. Photo album: Supports the cloud photo album function, import photos to the cloud disk, and then organize them for everyone to view.​

How to log in if Xiaohongshu only remembers the account? I just remember how to retrieve my account? How to log in if Xiaohongshu only remembers the account? I just remember how to retrieve my account? Mar 23, 2024 pm 05:31 PM

Xiaohongshu has now been integrated into the daily lives of many people, and its rich content and convenient operation methods make users enjoy it. Sometimes, we may forget the account password. It is really annoying to only remember the account but not be able to log in. 1. How to log in if Xiaohongshu only remembers the account? When we forget our password, we can log in to Xiaohongshu through the verification code on our mobile phone. The specific operations are as follows: 1. Open the Xiaohongshu App or the web version of Xiaohongshu; 2. Click the &quot;Login&quot; button and select &quot;Account and Password Login&quot;; 3. Click the &quot;Forgot your password?&quot; button; 4. Enter your account number. Click &quot;Next&quot;; 5. The system will send a verification code to your mobile phone, enter the verification code and click &quot;OK&quot;; 6. Set a new password and confirm. You can also use a third-party account (such as

What should I do if I can't log in to my account on Google Chrome? Solution to why Google Chrome account cannot be logged in What should I do if I can't log in to my account on Google Chrome? Solution to why Google Chrome account cannot be logged in Mar 13, 2024 pm 02:10 PM

What should I do if I can’t log in to my account on Google Chrome? When many users use this software, certain functions require users to log in to their Google account before they can use it. However, they have tried many times but failed to log in successfully. Faced with this problem, many users do not know how to solve it, so In this issue, the editor is here to share the solution with you. I hope that the content of today’s software tutorial can be helpful to everyone. The solution is as follows: 1. Click on a browser on the desktop, and after opening it, you will see something like this. 2. If a login pops up at this time, click it. If you can't see it, click the upper right corner. 3. Click Login, then enter your account number. You do not need to enter the account after @, and click Next. 4. Enter the password. When you see this prompt, click Enable

How to solve the common problem of Laravel login time invalidation How to solve the common problem of Laravel login time invalidation Mar 06, 2024 pm 09:24 PM

How to solve the common problem of Laravel login time expiration When using Laravel to develop web applications, login authentication is a very important function. However, sometimes if a user does not operate for a long time after logging in, the page may automatically log out or the authentication may fail. This problem is relatively common. The following will introduce how to solve this problem by setting the session time and provide specific code examples. 1. Set the session expiration time in Laravel, by default sessi

See all articles