How does react-navigation determine whether a user logs on to the logon page,

Source: Internet
Author: User

How does react-navigation determine whether a user logs on to the logon page,

This article describes how to use react-navigation to determine whether a user is logged on to the logon page, share the information with you, and take notes for yourself, as shown below:

Create an 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'; // global storage import stroage from '. /StorageUtil '; import '. /Global 'import IndexScreen from '. /Index 'import MeScreen from '. /Me 'import Login from '. /Login '// set const MainScr in the bottom menu bar EenNavigator = TabNavigator ({IndexScreen: {screen: IndexScreen, navigationOptions: {tabBarLabel: 'homepage', headerLeft: null, // remove the return button tabBarIcon: ({tintColor }) => (<Image source = {require ('. /img/ic_image.png ')} style = {[styles. icon, {tintColor: tintColor}]}/>), onNavigationStateChange :( () => alert ("Homepage") // initialRouteName: 'indexscreen'},}, MeScreen: {screen: MeScreen, navigationOptions: {tabB ArLabel: 'my', tabBarIcon: ({tintColor}) => (<Image source = {require ('. /img/ic_me.png ')} style = {[styles. icon, {tintColor: tintColor}]}/>), // initialRouteName: 'mescreen' }}, {// trueinitialRouteName: 'mescreen ', // set the default page component // initialRouteName: 'mescreen', lazy: true, // whether the tag is displayed as needed, rather than in advance, this means to load all the tabs at the bottom of the app when it is opened. The default value is false. It is recommended to be true // order: ['indexscreen', 'findscreen', 'listnewscreen ', 'screen '], // Order is used to define the order in which tabs are displayed. The array format is "animationEnabled: false". // whether the animation effect tabBarPosition: 'bottom 'is displayed at the bottom of the page is displayed, by default, android displays the swipeEnabled: false on the top of the page. // whether the tab can be swiped left or right. // backBehavior: 'none ', // press the back key to determine whether to jump to the first Tab (homepage). If none is set, do not jump to tabBarOptions: {activeTintColor: '#2196f3'. // The inactiveTintColor of the selected text and image: '#999', // The color showIcon: true is not selected for the text and image, and the icon is not displayed for android by default. You must set it to true to display indicatorStyle: {height: 0 // if there is a line shown below the TabBar, you can set the height to 0 and hide}, style: {backgroundColor: '# fff', // TabBar background color height: 60}, labelStyle: {fontSize: 14, // text size marginTop: 2 // lineHeight: 44 },}); // set const FirstApp = StackNavigator ({IndexScreen: {screen: mainScreenNavigator, // initialRouteName: 'indexscreen'}, MeScreen: {screen: MeScreen}, Login: {screen: Login}, },{ initialRouteName: 'indexscreen ', // default display interface nav IgationOptions: {// The default options for on-screen navigation. You can also use static navigationOptions in the component to set (the settings will be overwritten here) headerStyle: {elevation: 0, shadowOpacity: 0, height: 48, backgroundColor: "#2196f3"}, headerTitleStyle: {color: '# fff', fontSize: 16}, // alignSelf: 'center' text center headerBackTitleStyle: {color: '# fff', fontSize: 12}, // headerTintColor: {}, gesturesEnabled: true, // whether sliding and returning are supported, supported by iOS by default, disabled by Android by default}, mode: 'Card ', // page switching mode. The left and right are card (equivalent to push in iOS ). Effect), the upper and lower are modal (equivalent to the modal effect in iOS) headerMode: 'screen', // display mode in the navigation bar, screen: gradient transparent effect, float: no transparency effect, none: hides onTransitionStart: (Start) => {console. log ('navigation bar switchover start');}, // callback onTransitionEnd: () =>{ console. log ('end of navigation bar failed');} // callback}); // const defaultGetStateForAction = FirstApp. router. getStateForAction; FirstApp. router. getStateForAction = (action, state) =>{ // The page is MeScreen and global. user. loginState = fa Lse | ''(not logged on) if (action. routeName = 'screen '&&! Global. user. loginState) {this. routes = [... state. routes, {key: 'id-'+ Date. now (), routeName: 'login', params: {name: 'name1' }},]; return {... state, routes, index: this. routes. length-1 ,};}return defaultGetStateForAction (action, state) ;}; export default class FirstAppDemo extends Component {render () {return (<FirstApp/>) ;}} AppRegistry. registerComponent ('firstapp', () => FirstAppDemo); const styles = StyleSheet. create ({icon: {width: 26, height: 26 ,},});

Create a global storage StorageUtil. js

Import React, {Component} from 'react '; import {AsyncStorage} from 'react-native'; import Storage from 'react-native-store '; var storage = new Storage ({// maximum capacity. The default value is 1000 items. Circular storage size: 1000, // Storage engine: AsyncStorage for RN and window for web. localStorage // if not specified, the data will only be stored in the memory. After restart, the storageBackend: AsyncStorage will be lost. // The data expiration time, the default value is one full day (1000*3600*24 Ms). If it is set to null, defaultExpires will never expire: 1000*3600*24. // cache data in the memory during read/write operations. Enabled by default. EnableCache: true, // if no data exists in the storage, or the data has expired, // the corresponding sync method is called to seamlessly return the latest data. // The specific description of the sync method will be mentioned later // you can write the sync method here in the constructor // or write it to another file, here, require introduces // or, at any time, directly to storage. change the value of sync // sync: require ('. /sync ') // This sync file is written by yourself}) // it is best to create one (and only one) storage instance globally, convenient direct call // for web // window. storage = storage; // For react native // global. storage = storage; // in this way, you can directly call storage at any location after **. // Note: The global variable must be declared first, and then use // if you call storage somewhere, the error is undefined. // check global. whether the storage = storage statement has indeed been executed // export as the global variable. storage = storage; create a Global variable component. js. The user stores the user login information // The user login data global. user = {loginState: '', // logon status userData:'', // user data}; // obtain user data storage again when refreshing. load ({key: 'loginstate ',}). then (ret => {global. user. loginState = true; global. user. userData = ret ;}). catch (err => {global. user. loginState = false; global. user. userData = '';})

Log on to the Login. js component.

_ Login () {// logon function // debugger; ToastUtil. show ("Logon successful"); // use the key to save data. These data are generally globally unique and often need to be called. // Unless manually removed, the data will be permanently saved and will not expire by default. Storage. save ({key: 'loginstate', // Note: Do not use the _ underline in the key! Data: {userid: '000000', userName: 'username', token: 'Token'}, // if no expiration time is specified, the defaultExpires parameter will be used. // if it is set to null, it will never expire. // expires will expire after 8 hours: 1000*3600*8}); global. user. loginState = true; // set the logon status to global. user. userData = {userid: '000000', userName: 'username', token: 'Token'}; // Save User Data setTimeout () => {this. props. navigation. navigate ('userscreen') // jump to the user page}, 2000 )}

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.