7

Mục tiêu của tôi là chuyển hướng người dùng đến thành phần Home nếu người dùng đã đăng nhập. Tôi có thể đăng nhập người dùng và chuyển hướng họ đến Home chỉ khi _logInUser() được gọi . Tuy nhiên, khi được chuyển hướng đến thành phần Home, nếu tôi làm mới trình mô phỏng, ứng dụng sẽ quay lại thành phần Login.React Native - Chuyển hướng đã đăng nhập người dùng Firebase đến Thành phần nhà

Tôi đã cố gắng giải quyết vấn đề này bằng cách sử dụng componentWillMount() và đặt let user = firebaseApp.auth().currentUser. Tuy nhiên, tôi thậm chí đã đăng nhập user vào bảng điều khiển nhưng có vẻ như séc if chuyển thẳng đến câu lệnh else. Tôi sẽ đánh giá cao bất kỳ cái nhìn sâu sắc nào!

Đây là mã của tôi (Tôi đang sử dụng react-native-router-flux cho việc định tuyến):

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

Xin lỗi, tôi không có câu trả lời hoàn chỉnh cho bạn. Nhưng, tôi tin rằng [Tính năng chuyển đổi] (https://github.com/aksonov/react-native-router-flux/blob/master/docs/OTHER_INFO.md#switch-new-feature) có thể hữu ích ở đây. –

Trả lời

5

Thứ nhất, trong thành phần đăng nhập của bạn, bạn đang kiểm tra người dùng hiện tại theo cách đồng bộ, nhưng nó có thể chưa có sẵn có thể tại componentWillMount. Bạn có thể sẽ nhận được trong không đồng bộ:.

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

Nhiều khả năng nó sẽ đủ để gọi Actions.home() nếu người dùng đang đăng nhập Tuy nhiên, khi ứng dụng của bạn phát triển, bạn có thể muốn di chuyển logic này lên từ màn hình đăng nhập. Như Kyle đã đề xuất, bạn có thể sử dụng tính năng Chuyển đổi. Nó thường là (để tài liệu trích dẫn) được sử dụng với Redux, như thế này:

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

Nếu bạn không muốn sử dụng Redux, bạn có thể tự quấn Chuyển thay vì sử dụng phản ứng-Redux của kết nối và vượt qua LOGGEDIN chống đỡ để chuyển mạch . Ví dụ: bạn có thể nghe firebase trênAuthStateChanged trong trình bao bọc này, như sau:

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

Tôi thích giải pháp của bạn. Tôi đang cố gắng để thực hiện nó mà không có Redux và tôi nhận được lỗi này nói rằng 'kết nối là undefined'. Đây có phải là phương pháp Redux không? Làm thế nào tôi sẽ làm điều này mà không có Redux? Tôi đã tạo thành phần 'FirebaseSwitch' và nhập nó vào' index.ios.js' như bạn đã gợi ý. Cảm ơn một lần nữa !!! – szier

+0

Có, kết nối là từ phản ứng-redux. Thay thế RootSwitch bằng FirebaseSwitch trong các cảnh Router của bạn. –

+0

Rất cảm ơn bạn. Tôi đã làm điều đó nhưng im tò mò như thế nào 'rootSelector' có thể gọi' props.loggedIn' vì 'Scene' ban đầu được nạp bất cứ khi nào tôi tải lại trình mô phỏng luôn là' authScreens'. – szier

Các vấn đề liên quan