7

私の目標は、ユーザが既にログインしている場合にHomeコンポーネントにリダイレクトすることです。が呼び出された場合にのみ、ユーザにログインしてHomeにリダイレクトできます。 。しかし、一度Homeコンポーネントにリダイレクトされると、シミュレータをリフレッシュすると、アプリケーションはLoginコンポーネントに戻ります。React Native - ログインしたFirebaseユーザをホームコンポーネントにリダイレクト

componentWillMount()と設定してlet user = firebaseApp.auth().currentUserを使用して解決しようとしました。しかし、私はさらにuserをコンソールに記録しましたが、ifのチェックがelseのステートメントに直接向いているようです。私はどんな洞察にも感謝します!ここで

は私のコードは、(私はルーティングのためreact-native-router-fluxを使用しています)です:

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}` 
     ); 
     }); 
    } 
} 
+0

申し訳ありませんが、私は完全な答えはありません。しかし、私は[Switch Feature](https://github.com/aksonov/react-native-router-flux/blob/master/docs/OTHER_INFO.md#switch-new-feature)がここで役に立つと思います。 –

答えて

5

まず、中現在のユーザーを同期的にチェックしているログインコンポーネントですが、まだ利用できない可能性がありますcomponentWillMountで可能です。あなたは非同期で取得する必要がありますすることができます。

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

ユーザーがログインしている場合Actions.home()を呼び出すには十分だろうほとんどの場合しかし、あなたのアプリケーションを使用すると、ログイン画面からアップこのロジックを移動する場合があります大きくなるにつれて。 Kyleが提案したように、Switch機能を使用することができます。これは、通常、このようなReduxので使用し、(引用ドキュメントへ):あなたはReduxのを使用しない場合

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> 
); 

は、手動で代わりに反応し、再来の接続を使用してのスイッチをラップし、スイッチに小道具LOGGEDIN渡すことができます。たとえば、このラッパーのfirebase onAuthStateChangedを以下のように聞くことができます。

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}/>; 
    } 
} 
+0

私はあなたの解決策が好きです。私はReduxなしで実装しようとしていますが、 'connect is undefined'というエラーが出てきます。これはReduxメソッドですか?私はReduxなしでこれをどのようにして行いますか? 'FirebaseSwitch'コンポーネントを作成し、あなたの提案したように' index.ios.js'にインポートしました。再度、感謝します!!! – szier

+0

はい、接続はreact-reduxです。ルーターのシーンのRootSwitchをFirebaseSwitchに置き換えます。 –

+0

ありがとうございます。私はそれをしましたが、 'rootSelector'が' props.loggedIn'をどのように呼び出すことができるのか不思議でした。私がシミュレータをリロードするたびにロードされる最初の 'Scene'は常に' authScreens'です。 – szier

関連する問題