Javascript 如何在关闭和打开react本机应用程序后保持登录状态

Javascript 如何在关闭和打开react本机应用程序后保持登录状态,javascript,android,reactjs,react-native,firebase-authentication,Javascript,Android,Reactjs,React Native,Firebase Authentication,我正在react native上开发一个具有登录选项的应用程序。我正在使用firebase身份验证。我设法从firebase捕获了当前用户uid。我的问题是我不能一直待在这里。每次我打开应用程序,它都会让我一次又一次地登录 这是我的密码: 我知道我应该使用异步,但我不知道怎么做 import React from 'react'; import { StyleSheet, Text, View, TouchableOpacity, AsyncStorage, } from

我正在react native上开发一个具有登录选项的应用程序。我正在使用firebase身份验证。我设法从firebase捕获了当前用户uid。我的问题是我不能一直待在这里。每次我打开应用程序,它都会让我一次又一次地登录

这是我的密码:

我知道我应该使用异步,但我不知道怎么做

import React from 'react';
import { StyleSheet, 
  Text, 
  View, 
  TouchableOpacity,
  AsyncStorage,
} from 'react-native';
import {RkTextInput, RkButton } from 'react-native-ui-kitten';
import {Actions} from 'react-native-router-flux';
import { createSwitchNavigator, createAppContainer  } from 'react-navigation';

import Profile from "../Profile/Profile";
import * as firebase from 'firebase';

export default class Login extends React.Component {

  constructor(props){
    super(props)
    this.state=({
      email:'savadks1919@gmail.com',
      password:'123123',
      userId:'',
      errorMessage: null
    })
  }

  signup() {
    Actions.signup()
  }
  Home() {
    Actions.home()
  }

  handleLogin = (email, password) => {
    firebase.auth().signInWithEmailAndPassword(email, password).then(
      this.Home, 
      this.state=({userId:firebase.auth().currentUser.uid})
    ).catch(function(error) {
      var errorCode = error.code;
      var errorMessage = error.message;

      if (errorCode === 'auth/wrong-password') {
        alert('Wrong password.');
        } else {
          alert(errorMessage);         
        }
      console.log(error);
    });
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.titleText}>Taams</Text>
        <Text style={styles.edition}>Developer's Edition</Text>
        <Text style={styles.titleText}>Login.js</Text>
        <Text>Alpha 0.0.0.1</Text>

        {/*-----UserName Input-------*/}
        <RkTextInput 
          rkType= 'rounded' 
          labelStyle= {{color: 'black', fontWeight: 'bold'}}
          placeholder='UserName'
          //--------------value Handler----------------//
          onChangeText={(email) => this.setState({email})}
          //---------------------------------//
          selectionColor="#000000"
          keyboardType="email-address"
          onSubmitEditing={() => { this.password.focusInput(); }}
          inputStyle={{
            color: 'black',
            fontWeight: 'bold',
          }}/>

        {/*-----Password-------*/}
        <RkTextInput 
          secureTextEntry={true}
          rkType= 'rounded' 
          placeholder='Password'
          //--------------value Handler----------------//
          onChangeText={(password) => this.setState({password})}
          //---------------------------------//
          ref={(input) => { this.password = input; }}
          inputStyle={{
            color: 'black',
            fontWeight: 'bold',
          }}/>

        <RkButton onPress = {()=>this.handleLogin(this.state.email,this.state.password)}>
          <Text style={styles.LoginButtonText}>Login</Text>
        </RkButton>

        <View style={styles.signupTextCont}>
          <Text style={styles.signupText}>Don't have an account yet?</Text>
          <TouchableOpacity onPress={this.signup}><Text style={styles.signinButton}>SignUp</Text></TouchableOpacity> 
        </View>
      </View>  
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
  signupTextCont:{
    flexGrow: 0,
    alignItems:'center',
    justifyContent:'flex-end',
    marginVertical:15
  },
  signupText:{
    color:'rgba(64,64,64,0.6)',
    fontSize:16
  },
  signinButton:{
    color:'#000000',
    fontSize:16,
    fontWeight:'500'
  },
  titleText: {
    fontSize: 20,
    fontWeight: 'bold',
  },
  edition: {
    fontSize: 15,
  },
  TextInput: {
    width: 300,
    height:50,
    borderColor: 'grey',
    borderWidth: 1,
  },
  LoginButtonText: {
    fontSize: 20,
    fontWeight: 'bold',
    color: 'white',  
  },
});
从“React”导入React;
导入{样式表,
文本,
看法
可触摸不透明度,
异步存储,
}从“反应本机”;
从“react native ui kitten”导入{RkTextInput,RkButton};
从“react native router flux”导入{Actions};
从“react navigation”导入{createSwitchNavigator,createAppContainer};
从“./Profile/Profile”导入配置文件;
从“firebase”导入*作为firebase;
导出默认类登录扩展React.Component{
建造师(道具){
超级(道具)
这个州=({
电邮:'savadks1919@gmail.com',
密码:'123123',
用户标识:“”,
错误消息:空
})
}
注册(){
行动。注册()
}
Home(){
行动.主页()
}
handleLogin=(电子邮件、密码)=>{
firebase.auth().使用email和password(电子邮件,密码)登录。然后(
这个家,,
this.state=({userId:firebase.auth().currentUser.uid})
).catch(函数(错误){
var errorCode=error.code;
var errorMessage=error.message;
如果(错误代码==='auth/错误密码'){
警报(“密码错误”);
}否则{
警报(错误消息);
}
console.log(错误);
});
}
render(){
返回(
塔姆斯
开发者版
Login.js
阿尔法0.0.0.1
{/*----用户名输入------*/}
this.setState({email})}
//---------------------------------//
selectionColor=“#000000”
keyboardType=“电子邮件地址”
onSubmitEditing={()=>{this.password.focusInput();}}
输入样式={{
颜色:'黑色',
fontWeight:'粗体',
}}/>
{/*----密码------*/}
this.setState({password})}
//---------------------------------//
ref={(输入)=>{this.password=input;}}
输入样式={{
颜色:'黑色',
fontWeight:'粗体',
}}/>
this.handleLogin(this.state.email,this.state.password)}>
登录
你还没有账户吗?
报名
);
}
}
const styles=StyleSheet.create({
容器:{
弹性:1,
背景颜色:“#fff”,
对齐项目:“居中”,
为内容辩护:“中心”,
},
signupTextCont:{
flexGrow:0,
对齐项目:'中心',
辩护内容:'flex-end',
利润率:15
},
登录文本:{
颜色:'rgba(64,64,64,0.6)',
字体大小:16
},
登录按钮:{
颜色:'#000000',
尺寸:16,
重量:'500'
},
标题文字:{
尺寸:20,
fontWeight:'粗体',
},
版本:{
尺寸:15,
},
文本输入:{
宽度:300,
身高:50,
边框颜色:“灰色”,
边框宽度:1,
},
登录按钮文本:{
尺寸:20,
fontWeight:'粗体',
颜色:'白色',
},
});

将从firebase登录请求获得的用户ID存储在异步存储中,如

Home(userId) {
 (async ()=>{
  await AsyncStorage.setItem("userId",userId)
  Actions.home()
 })()
}
redirectToHome() {
 (async ()=>{
   let userId = await AsyncStorage.getItem("userId",userId)
   if(userId){
    Actions.home()
   }
   else {
    //redirect to login page
   }
 })()
}
AsyncStorage.clear()
然后下次打开应用程序时检查异步存储,如

Home(userId) {
 (async ()=>{
  await AsyncStorage.setItem("userId",userId)
  Actions.home()
 })()
}
redirectToHome() {
 (async ()=>{
   let userId = await AsyncStorage.getItem("userId",userId)
   if(userId){
    Actions.home()
   }
   else {
    //redirect to login page
   }
 })()
}
AsyncStorage.clear()
注销时清除异步存储,如

Home(userId) {
 (async ()=>{
  await AsyncStorage.setItem("userId",userId)
  Actions.home()
 })()
}
redirectToHome() {
 (async ()=>{
   let userId = await AsyncStorage.getItem("userId",userId)
   if(userId){
    Actions.home()
   }
   else {
    //redirect to login page
   }
 })()
}
AsyncStorage.clear()

在异步存储中存储从firebase登录请求获得的用户ID,如

Home(userId) {
 (async ()=>{
  await AsyncStorage.setItem("userId",userId)
  Actions.home()
 })()
}
redirectToHome() {
 (async ()=>{
   let userId = await AsyncStorage.getItem("userId",userId)
   if(userId){
    Actions.home()
   }
   else {
    //redirect to login page
   }
 })()
}
AsyncStorage.clear()
然后下次打开应用程序时检查异步存储,如

Home(userId) {
 (async ()=>{
  await AsyncStorage.setItem("userId",userId)
  Actions.home()
 })()
}
redirectToHome() {
 (async ()=>{
   let userId = await AsyncStorage.getItem("userId",userId)
   if(userId){
    Actions.home()
   }
   else {
    //redirect to login page
   }
 })()
}
AsyncStorage.clear()
注销时清除异步存储,如

Home(userId) {
 (async ()=>{
  await AsyncStorage.setItem("userId",userId)
  Actions.home()
 })()
}
redirectToHome() {
 (async ()=>{
   let userId = await AsyncStorage.getItem("userId",userId)
   if(userId){
    Actions.home()
   }
   else {
    //redirect to login page
   }
 })()
}
AsyncStorage.clear()

此代码主要有助于保持应用程序处于登录状态

Login.js

首先导入异步存储并运行npm安装

1.npm添加@react本机社区/异步存储

import AsyncStorage from '@react-native-community/async-storage';
2.react-native链接@react-native社区/异步存储

import AsyncStorage from '@react-native-community/async-storage';
在您的登录功能中输入以下代码

setAsyncStorage(){   //set the value to async storage 

  try {
     AsyncStorage.setItem('isLoggedIn', 'YES');        
    this.props.navigation.navigate("Home");  //(optional)
  } catch (error) {
    console.log(error);
  }
}; 
现在将下面的代码放入componentDidMount()中以获取asyncStorage值

componentDidMount(){
       SplashScreen.hide();  //(optional)
            AsyncStorage.getItem('isLoggedIn').then((value) => {
        if(value && value === 'YES') {
          alert(value)  //(Hide it once you get value from this)
          this.props.navigation.navigate("Home")

        } else {

        }
      })
}
要注销,请在主页中使用它

Home.js

import AsyncStorage from '@react-native-community/async-storage';


    logout(){
         this.props.navigation.navigate("Login")
        AsyncStorage.clear()

    }

此代码主要有助于保持应用程序处于登录状态

Login.js

首先导入异步存储并运行npm安装

1.npm添加@react本机社区/异步存储

import AsyncStorage from '@react-native-community/async-storage';
2.react-native链接@react-native社区/异步存储

import AsyncStorage from '@react-native-community/async-storage';
在您的登录功能中输入以下代码

setAsyncStorage(){   //set the value to async storage 

  try {
     AsyncStorage.setItem('isLoggedIn', 'YES');        
    this.props.navigation.navigate("Home");  //(optional)
  } catch (error) {
    console.log(error);
  }
}; 
现在将下面的代码放入componentDidMount()中以获取asyncStorage值

componentDidMount(){
       SplashScreen.hide();  //(optional)
            AsyncStorage.getItem('isLoggedIn').then((value) => {
        if(value && value === 'YES') {
          alert(value)  //(Hide it once you get value from this)
          this.props.navigation.navigate("Home")

        } else {

        }
      })
}
要注销,请在主页中使用它

Home.js

import AsyncStorage from '@react-native-community/async-storage';


    logout(){
         this.props.navigation.navigate("Login")
        AsyncStorage.clear()

    }

谢谢你的重播。。。你能用我提供的代码演示一下吗。。因为我是新手,编程能力非常差\更新了我的解决方案,使用立即调用的功能执行异步功能感谢您的重播。。。你能用我提供的代码演示一下吗。。因为我是新手,编程能力非常差\更新了我的解决方案,使用立即调用的功能来执行异步函数