javascript - 如何在关闭和打开后在 react native 应用程序上保持登录状态

标签 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';
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',  
  },
});

最佳答案

在 AsyncStorage 中存储从 Firebase 登录请求获取的 userId,例如

Home(userId) {
 (async ()=>{
  await AsyncStorage.setItem("userId",userId)
  Actions.home()
 })()
}

然后下次打开应用程序时检查 AsyncStorage,例如

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

注销时清除 AsyncStorage 就像

AsyncStorage.clear()

关于javascript - 如何在关闭和打开后在 react native 应用程序上保持登录状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54364609/

相关文章:

javascript - d3js : Bar charts are not visible and no errors are showing up

android - 如何检测是否支持MediaRecorder.AudioEncoder.HE_AAC?

post - 如何使用 React Router HistoryLocation 配置 Nginx?

android - 如何在此代码上为 FragmentTransaction 设置自定义动画

android - 使用 halninja ffmpeg 在 Android 中连接 mp4 文件

javascript - 所有图像都会被删除,而不是在reactjs中单击删除图标的特定图像

javascript - 我们如何处理来自错误的不同 HTTP 响应?

javascript - 在 ie8 中使用 e.target.tagName 或 .prop 的问题

javascript - 如何为以下代码片段编写单元测试用例

javascript - Axios 和推特 API