根据用户身份验证重定向用户

时间:2019-06-20 13:05:44

标签: react-native axios

在我的本地本机应用程序中,我想检查用户之前是否已经登录,然后必须将其直接重定向到“主页”,而无需再次要求他提供凭据。 “主页”组件由边栏中的注销按钮组成。

我当前的代码可以很好地用于新用户登录,但是我在如何检查用户是否再次打开应用程序上停留不动,他的登录令牌应保持不变,并且必须将其直接重定向到“主页”。

这是我的代码:

import React, { Component } from 'react'
import { Text, View, Image, TextInput, TouchableOpacity, ScrollView, AsyncStorage, ToastAndroid } from 'react-native'
import axios from 'axios';

export default class Login extends Component {

    constructor(){
        super();

        this.state = {
            username: '',
            password: '',
            isLoggedIn: false,
            loginChecked: false,
        }
    }

    componentDidMount(){
        this.getItem('userID');
    }


    //function to extract storage token. Any name can be given ot it. 
    async getItem(item){
        console.log('method ran login screen');
        console.log(this.state.isLoggedIn)
        try{
            const value = await AsyncStorage.getItem(item);
            if(value !== null){
                this.setState({
                    isLoggedIn: true,
                    loginChecked: true
                })

            }
            else{
                this.setState({
                    isLoggedIn: false,
                    loginChecked: true
                })
            }
        }
        catch(error){
            console.log(error)
        }
        console.log(this.state.isLoggedIn)
    }

    //function to remove storage token 
    async removeItem(item){
        try{
            const value = await AsyncStorage.removeItem(item);

            if(value == null){
                this.setState({
                    isLoggedIn: false
                })
            }
        }
        catch(error){
            //handle errors here
        }
    }



    userLogin = () => {

        if(this.state.username != '' && this.state.password != ''){
            axios.post('http://bi.servassure.net/api/login', {
            username: this.state.username,
            password: this.state.password
        })
        .then(res => {

            let userToken = res.data.token;
            console.log(res.data);

            if(res.data.success){
                AsyncStorage.setItem('userID', userToken);
                this.setState({
                    isLoggedIn: true
                })
                this.props.navigation.navigate('Home');
            }
            else{
                ToastAndroid.showWithGravity(
                    'Invalid login' ,
                    ToastAndroid.SHORT,
                    ToastAndroid.CENTER
                  );
            }
        })
        .catch(err => {
            console.log(err);
        });

        }
        else{
            ToastAndroid.showWithGravity(
                'Please Enter Credentials' ,
                ToastAndroid.SHORT,
                ToastAndroid.CENTER
              );
        }
    }


    logOut(){
        this.removeItem('userID');
    }

    render() {
        return (
            <ScrollView>
                <View style={{justifyContent:'center', alignItems:'center'}}>

                    <View style={{marginVertical:20}}>
                        <Text>
                            Login to your account
                        </Text>
                    </View>


                    <View>
                        <TextInput 
                            style={{width: 300, height: 50, borderColor: 'gray', borderWidth: 1, borderRadius: 10, marginVertical: 10}}
                            onChangeText={(username) => this.setState({username})}
                            placeholder='username'
                            autoCapitalize = 'none'
                        />

                        <TextInput 
                            style={{width: 300, height: 50, borderColor: 'gray', borderWidth: 1, borderRadius: 10}}
                            onChangeText={(password) => this.setState({password})}
                            placeholder='password'
                            secureTextEntry={true}
                        />
                    </View>

                    <View style={{justifyContent: 'center', alignItems: 'center'}}>
                        <TouchableOpacity 
                        style={{width: 300, height: 50, borderWidth:1, borderRadius: 50, borderColor: 'gray', justifyContent: 'center', alignItems: 'center', marginVertical: 10}}

                        onPress={this.userLogin}>

                            <Text>
                                LOGIN
                            </Text>

                        </TouchableOpacity>
                        <Text>Forget Password</Text>
                    </View>
                </View>
            </ScrollView>
        )
    }
}

另外,我在登录前有一个SplashScreen:

import React, { Component } from 'react'
import { Text, View } from 'react-native'

export default class SplashScreen extends Component {

    componentDidMount(){

        setTimeout( () => {
            this.props.navigation.navigate('Login')
        }, 2000)

    }

    render() {
        return (
            <View style={styles.viewStyles}>
                <Text style={styles.textStyles}> My App </Text>
            </View>
        )
    }
}


const styles = {
    viewStyles: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      backgroundColor: 'orange'
    },
    textStyles: {
      color: 'white',
      fontSize: 40,
      fontWeight: 'bold'
    }
  }

我对本机反应有点陌生,请帮忙弄清楚。

2 个答案:

答案 0 :(得分:2)

在您的 Login.js 文件中执行以下操作:

import {AsyncStorage} from react-native;

获得成功的登录API响应后,您可以执行以下操作:

AsyncStorage.setItem('userID', responsejson.user_detail.userID);

以相同的方式,您也可以存储令牌

AsyncStorage.setItem('token', responsejson.user_detail.token);

然后在您的 splashscreen.js 中,以与上述相同的方式导入AsyncStorage,然后将此代码放入 componentWillMount()或componentDidMount()

您的 splashscreen.js

 var value =  AsyncStorage.getItem('token');
    value.then((e)=>{

    if (e == '' || e == null ){
         this.props.navigation.replace('Login')          
    }else {
       this.props.navigation.replace('Home')
    }
    })

说明 :加载splashscreen.js时,它将检查asyncstorage中的令牌,如果获取令牌,则导航到主屏幕,否则导航到登录屏幕。 / p>

答案 1 :(得分:1)

导入React Navigation库并使用Switch Navigator。它旨在根据用户的登录状态处理应用程序导航。

This article explains everything with examples