React Native - 将登录的Firebase用户重定向到Home组件 [英] React Native - Redirect logged in Firebase user to Home Component

查看:299
本文介绍了React Native - 将登录的Firebase用户重定向到Home组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是将用户重定向到 Home 组件,如果用户已经登录了。我可以登录一个用户并将它们重定向到<$ c $只有在调用 _logInUser()时,才能使用c> Home 但是,一旦重定向到 Home 组件,如果刷新模拟器,应用程序将返回到 Login 组件。 / p>

我尝试使用 componentWillMount()并设置 let user = firebaseApp.auth ().currentUser 。然而,我甚至将用户记录到控制台,但是如果检查直接到 else 语句。

这里是我的代码(我正在使用 react-native-router-flux 路线):

index.ios.js

 从'react'导入React,{Component}; 
从'react-native-router-flux'导入{Scene,Router};
从'react-native'导入{
AppRegistry,
};

//组件
导入从./components/user/login/login中登录;
从'./components/user/home/home'导入首页;

class AppName extends Component {
render(){
return(
< Router>
< Scene key =root>
< Scene key =logincomponent = {Login} title =LoginhideNavBar = {true} initial = {true} />
< / Scene>
< / Router>
);



$ b AppRegistry.registerComponent('AppName',()=> AppName);

login.js

 从'react'导入React,{Component}; 
导入{
AlertIOS,
尺寸,
图片,
ScrollView,
样式表,
文本,
TextInput,
TouchableOpacity,
从'react-native'查看
};

从'react-native-keyboard-aware-scroll-view'导入{KeyboardAwareScrollView};
从'react-native-router-flux'导入{Actions};

从'AppName / firebase_setup'导入firebaseApp;

//将宽度和高度设置为屏幕尺寸
const {width,height} = Dimensions.get(window);

//对于Firebase Auth
const auth = firebaseApp.auth();

//删除StackOverflow的样式

导出默认类登录延伸组件{
构造函数(道具){
super(道具);

this.state = {
email:'',
密码:''
}
}

componentWillMount( ){
let user = auth.currentUser;
if(user!= null){
console.log(user);
Actions.home
} else {
return; (



$ b $(b
$返回(
< View style = {styles.mainContainer}>
< KeyboardAwareScrollView
style = {styles.scrollView}
keyboardShouldPersistTaps = {false}
automaticallyAdjustContentInsets = {true}
alwaysBonceVertical = {false}
>
< b< ; View style = {styles.loginContainer}>

< View style = {styles.inputContainer}>

< TextInput
style = {styles .formInput}
placeholder =Email
keyboardType =email-address
autoFocus = {true}
autoCorrect = {false}
autoCapitalize =none
onChangeText = {(email)=> this.setState({email})}
/>

< TextInput
style = {styles.formInput }
secureTextE ntry = {true}
placeholder =Password
autoCorrect = {false}
autoCapitalize =none
onChangeText = {(password)=> this.setState({password})}
/>

< TouchableOpacity
style = {styles.loginButton}
onPress = {this._logInUser.bind(this)}
>
< Text style = {styles.loginButtonText}>登入< / Text>
< / TouchableOpacity>

< TouchableOpacity>
<文字样式= {styles.toSignupButton}>没有帐号?创建一个!< / Text>
< / TouchableOpacity>

< / View>
< / View>

< View style = {styles.footer}>
< Text style = {styles.footerText}>
通过注册,我同意TextbookSwap的< Text style = {styles.footerActionText}>服务条款< / Text>和< Text style = {styles.footerActionText}>隐私政策< / Text> ;.
< / Text>
< / View>
< / KeyboardAwareScrollView>
< / View>
);
}

_logInUser(){
let email = this.state.email;
让密码= this.state.password;

auth.signInWithEmailAndPassword(email,password)
.then(Actions.home)
.catch((error)=> {
AlertIOS.alert(
`$ {error.code}`,
`$ {error.message}`
);
});


$ / code $ / pre

解决方案

,在你的登录组件中,你正以同步的方式检查currentUser,但是它可能还没有在componentWillMount上可用。您可以异步进入:

$ p $ firebase.auth()。onAuthStateChanged(function(user){
if(用户){
//用户已经登录
} else {
//没有用户登录
}
});

最有可能调用 Actions.home() code>如果用户登录。但是,随着你的应用程序的增长,你可能想从登录屏幕上移动这个逻辑。正如Kyle所建议的那样,您可以使用Switch功能。通常情况下(引用docs)与redux一起使用,就像这样:
$ b $ $ $ $ $ codeonst RootSwitch = connect(state =>({ loggedIn:state.transient.loggedIn}))(Switch);
const rootSelector = props => props.loggedIn? 'workScreens':'authScreens';

const scenes = Actions.create(
< Scene key =roottabs = {true} component = {RootSwitch} selector = {rootSelector}>
< Scene key =authScreenshideNavBar = {true}>

...
< / Scene>
< Scene key =workScreens>
< Scene key = component = {Home} initial = {true} />
< Scene key =profilecomponent = {ProfileMain} />
...
< / Scene>
< / Scene>
);

如果您不想使用redux,则可以手动换行而不是使用react-redux连接并通过登录道具到交换机。例如,你可以在这个包装器中听取firebase onAuthStateChanged,如下所示:

  class FirebaseSwitch extends Component {

state = {
loggenIn:false
}
$ b $ componentWillMount(){
firebase.auth()。onAuthStateChanged(user =>
this.setState({loggedIn:!! user})
);


render(){
return< Switch loggedIn = {this.state.loggedIn} {... this.props} /> ;;
}
}


My goal is to redirect the user to the Home component if the user is already logged in. I am able to login a user and redirect them to Home only if _logInUser() is called. However, once redirected to the Home component, if I refresh the simulator the app goes back to the Login component.

I attempted to solve this using componentWillMount() and setting let user = firebaseApp.auth().currentUser. However, I even logged the user to the console but it seems like the if check goes straight to the else statement. I would appreciate any insight!

Here is my code (I am using react-native-router-flux for routing):

index.ios.js

import React, { Component } from 'react';
import { Scene, Router } from 'react-native-router-flux';
import {
  AppRegistry,
} from 'react-native';

// Components
import Login from './components/user/login/login';
import Home from './components/user/home/home';

class AppName extends Component {
  render() {
    return (
      <Router>
        <Scene key="root">
          <Scene key="login" component={Login} title="Login" hideNavBar={true} initial={true}/>
          <Scene key="home" component={Home} title="Home"/>
        </Scene>
      </Router>
    );
  }
}


AppRegistry.registerComponent('AppName', () => AppName);

login.js

import React, { Component } from 'react';
import {
  AlertIOS,
  Dimensions,
  Image,
  ScrollView,
  StyleSheet,
  Text,
  TextInput,
  TouchableOpacity,
  View
} from 'react-native';

import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import { Actions } from 'react-native-router-flux';

import firebaseApp from 'AppName/firebase_setup';

// Set width and height to screen dimensions
const { width, height } = Dimensions.get("window"); 

// For Firebase Auth
const auth = firebaseApp.auth();

// Removed styles for StackOverflow

export default class Login extends Component {
  constructor(props) {
    super(props);

    this.state = {
      email: '',
      password: ''
    }
  }

  componentWillMount() {
    let user = auth.currentUser;
    if (user != null) {
      console.log(user);
      Actions.home
    } else {
      return;
    }
  }

  render() {
    return (
      <View style={styles.mainContainer}>
        <KeyboardAwareScrollView 
          style={styles.scrollView}
          keyboardShouldPersistTaps={false}
          automaticallyAdjustContentInsets={true}
          alwaysBonceVertical={false}
        >
          <View style={styles.loginContainer}>

            <View style={styles.inputContainer}>

              <TextInput
                style={styles.formInput}
                placeholder="Email"
                keyboardType="email-address"
                autoFocus={true}
                autoCorrect={false}
                autoCapitalize="none"
                onChangeText={(email) => this.setState({email})}
              />

              <TextInput
                style={styles.formInput}
                secureTextEntry={true}
                placeholder="Password"
                autoCorrect={false}
                autoCapitalize="none"
                onChangeText={(password) => this.setState({password})}
              />

              <TouchableOpacity 
                style={styles.loginButton}
                onPress={this._logInUser.bind(this)}
              >
                <Text style={styles.loginButtonText}>Log In</Text>
              </TouchableOpacity>

              <TouchableOpacity>
                <Text style={styles.toSignupButton}>Dont have an account? Create one!</Text>
              </TouchableOpacity>

            </View>
          </View>

          <View style={styles.footer}>
            <Text style={styles.footerText}>
              By signing up, I agree to TextbookSwap's <Text style={styles.footerActionText}>Terms of Service</Text> and <Text style={styles.footerActionText}>Privacy Policy</Text>.
            </Text>
          </View>
        </KeyboardAwareScrollView>
      </View>
    );
  }

  _logInUser() {
    let email = this.state.email;
    let password = this.state.password;

    auth.signInWithEmailAndPassword(email, password)
      .then(Actions.home)
      .catch((error) => {
        AlertIOS.alert(
          `${error.code}`,
          `${error.message}`
        );
      });
  }
}

解决方案

First, in your login component you are checking currentUser in synchronous way, but it might be not yet available at componentWillMount. You can should get in asynchronously:

firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
    // User is signed in.
  } else {
    // No user is signed in.
  }
});

Most likely it will be enough to call Actions.home() if user is logged in. However, as your app grows you might want to move this logic up from Login screen. As Kyle suggested, you can use Switch feature. It is usually (to quote docs) used with redux, like this:

const RootSwitch = connect(state => ({loggedIn: state.transient.loggedIn}))(Switch);
const rootSelector = props => props.loggedIn ? 'workScreens' : 'authScreens';

const scenes = Actions.create(
   <Scene key="root" tabs={true} component={RootSwitch} selector={rootSelector}>
     <Scene key="authScreens" hideNavBar={true}>
       <Scene key="login" component={Login} initial={true}/>
       <Scene key="register" component={Register} />
       ...
     </Scene>
     <Scene key="workScreens">
       <Scene key="home" component={Home} initial={true}/>
       <Scene key="profile" component={ProfileMain}/>
       ...
     </Scene>
   </Scene>
);

If you don't want to use redux, you can manually wrap Switch instead of using react-redux's connect and pass loggedIn prop to Switch. For example, you can listen to firebase onAuthStateChanged in this wrapper, something like this:

class FirebaseSwitch extends Component {

  state = {
    loggenIn: false
  }

  componentWillMount() {
    firebase.auth().onAuthStateChanged( user =>
      this.setState({loggedIn: !!user})
    );
  }

  render() {
    return <Switch loggedIn={this.state.loggedIn} {...this.props}/>;
  }
}

这篇关于React Native - 将登录的Firebase用户重定向到Home组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆