如果已登录,则React Native Firebase更改initialRoute

时间:2016-11-04 02:53:24

标签: firebase react-native firebase-authentication

我正在使用React Native 0.36和Firebase。如果用户登录,如何更改应用程序的主页。我在renderScene中尝试了if语句,但它出现此错误:

React Native Firebase initialRoute error

index.ios.js

import React, { Component } from 'react';

import {
  AppRegistry,
  Navigator,
} from 'react-native';

import firebase from 'firebase';
import Login from './Login';
import Home from './Home';

function renderScene(route, navigator) {
    return <route.component route={route} navigator={navigator} />;
}

export default class Snip extends Component {
  renderScene(route, navigator){ 
      return <route.component navigator={navigator} />
  }

  render() {
    var that = this;
    firebase.auth().onAuthStateChanged(function(user) {
      if(user) {
        return (
          <Navigator
            initialRoute={{component: Home}}
            renderScene={that.renderScene}/>
        )
      } else{
        return (
          <Navigator
            initialRoute={{component: Login}}
            renderScene={that.renderScene}/>
        )
      }
    });
  }
}

1 个答案:

答案 0 :(得分:1)

问题中的代码有两个问题。

  1. 您无法在firebase回调中返回react元素
  2. 如果用户存在,Firebase需要一些时间才能返回。所以我必须创建一个更新的加载状态。当firebase完成时。
  3. index.ios.js

      import React, { Component } from 'react';
    
      import {
        AppRegistry,
        Navigator,
        View,
        Text,
      } from 'react-native';
    
      import firebase from 'firebase';
      import Login from './Login';
      import Home from './Home';
    
    
      function renderScene(route, navigator) {
          return <route.component route={route} navigator={navigator} />;
      }
    
      export default class Snip extends Component {
        constructor(props) {
          super(props);
          this.state = { 
            user: null,
            loading: false
          };
        }
    
        componentWillMount() {
          var that = this;
          firebase.auth().onAuthStateChanged(function(user) {
            if(user) {
              that.setState({
                user: user,
                loading: false
              })
            }else{
              that.setState({
                loading: false
              })
            }
          });
        }
    
        renderScene(route, navigator){ 
            return <route.component navigator={navigator} />
        }
    
        render() {
          if(this.state.loading){
            return <View><Text>loading</Text></View>;
          }else if(this.state.user){
            return(
              <Navigator
                initialRoute={{component: Home}}
                renderScene={this.renderScene}/>
              )
          }else{
             return (
               <Navigator
                 initialRoute={{component: Login}}
                 renderScene={this.renderScene}/>
             )   
          }
        }
      }