React native 基于用户身份验证重定向用户

React native 基于用户身份验证重定向用户,react-native,axios,React Native,Axios,在我的react本机应用程序中,我想检查用户是否已经登录过,然后必须将其直接重定向到“主页”,而无需再次询问其凭据。“主页”组件由侧栏中的注销按钮组成 我当前的代码对新用户登录很好,但我一直在研究如何检查用户是否再次打开应用程序,他的登录令牌是否应该保留,他必须直接重定向到“主页” 这是我的密码: import React, { Component } from 'react' import { Text, View, Image, TextInput, TouchableOpacity, Sc

在我的react本机应用程序中,我想检查用户是否已经登录过,然后必须将其直接重定向到“主页”,而无需再次询问其凭据。“主页”组件由侧栏中的注销按钮组成

我当前的代码对新用户登录很好,但我一直在研究如何检查用户是否再次打开应用程序,他的登录令牌是否应该保留,他必须直接重定向到“主页”

这是我的密码:

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>
        )
    }
}
import React,{Component}来自“React”
从“react native”导入{Text,View,Image,TextInput,TouchableOpacity,ScrollView,AsyncStorage,ToastAndroid}
从“axios”导入axios;
导出默认类登录扩展组件{
构造函数(){
超级();
此.state={
用户名:“”,
密码:“”,
伊斯洛格丁:错,
登录检查:错误,
}
}
componentDidMount(){
this.getItem('userID');
}
//函数提取存储令牌。可以为其指定任何名称。
异步getItem(项目){
log('method run login screen');
console.log(this.state.isLoggedIn)
试一试{
const value=await AsyncStorage.getItem(项);
如果(值!==null){
这是我的国家({
伊斯洛格丁:是的,
登录检查:正确
})
}
否则{
这是我的国家({
伊斯洛格丁:错,
登录检查:正确
})
}
}
捕获(错误){
console.log(错误)
}
console.log(this.state.isLoggedIn)
}
//删除存储令牌的函数
异步removeItem(项目){
试一试{
常量值=等待异步存储.removietem(项);
如果(值==null){
这是我的国家({
伊斯洛格丁:错
})
}
}
捕获(错误){
//在这里处理错误
}
}
用户登录=()=>{
if(this.state.username!=''&&this.state.password!=''){
轴心柱http://bi.servassure.net/api/login', {
用户名:this.state.username,
密码:this.state.password
})
。然后(res=>{
让userToken=res.data.token;
console.log(res.data);
if(res.data.success){
AsyncStorage.setItem('userID',userToken);
这是我的国家({
伊斯洛格丁:是的
})
this.props.navigation.navigate('Home');
}
否则{
用重力来展示(
“无效登录”,
ToastAndroid.SHORT,
ToastAndroid.CENTER
);
}
})
.catch(错误=>{
控制台日志(err);
});
}
否则{
用重力来展示(
'请输入凭据',
ToastAndroid.SHORT,
ToastAndroid.CENTER
);
}
}
注销(){
this.removietem('userID');
}
render(){
返回(
登录到您的帐户
this.setState({username})}
占位符='username'
自动资本化='无'
/>
this.setState({password})}
占位符=“密码”
secureTextEntry={true}
/>
登录
忘记密码
)
}
}
此外,我在登录前有一个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'
    }
  }
import React,{Component}来自“React”
从“react native”导入{Text,View}
导出默认类SplashScreen扩展组件{
componentDidMount(){
设置超时(()=>{
this.props.navigation.navigate('Login'))
}, 2000)
}
render(){
返回(
我的应用程序
)
}
}
常量样式={
视图样式:{
弹性:1,
对齐项目:“居中”,
为内容辩护:“中心”,
背景颜色:“橙色”
},
文本样式:{
颜色:'白色',
尺寸:40,
fontWeight:“粗体”
}
}

我对react native有点陌生,请帮助解决这个问题。

在您的Login.js文件中执行类似操作:

import {AsyncStorage} from react-native;
在获得登录API的响应成功后,您可以执行以下操作:

AsyncStorage.setItem('userID', responsejson.user_detail.userID);
同样,您也可以存储令牌

AsyncStorage.setItem('token', responsejson.user_detail.token);
然后在您的splashscreen.js中,以与上面相同的方式导入异步存储,然后将此代码放入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中的令牌,如果获得令牌,则导航到主屏幕,否则导航到登录屏幕。

导入React导航库并使用交换机导航器。它设计用于根据用户的登录状态处理应用程序导航


将令牌存储在某个地方(redux、文件系统等),一旦用户返回,只要重定向令牌是否仍然有效(未过期)。您能为我提供一些代码片段吗。没有redux?每次应用程序变为“活动”时,您都可以使用react native中的AppState检查令牌。您需要在componentDi中附加一个侦听器