Home > Web Front-end > JS Tutorial > body text

React-navigation determines whether the user is logged in and jumps to the login page. Example sharing

小云云
Release: 2018-01-05 10:49:08
Original
3902 people have browsed it

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. I hope it can help everyone.

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 new 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

Related recommendations:

React Native react-navigation Navigation usage details

How to use the navigation component react-navigation

How to solve the problem that internal tabs cannot switch normally when multiple tabs are nested in react-navigation

The above is the detailed content of React-navigation determines whether the user is logged in and jumps to the login page. Example sharing. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!