反应不渲染if块内的组件

时间:2018-07-07 10:42:43

标签: javascript reactjs firebase-authentication

我正在尝试使用Firebase创建受保护的路由组件,我具有以下设置

import React, { Component } from 'react';
import { Route, Redirect } from 'react-router-dom';

import firebase from 'firebase';

firebase.initializeApp({
    apiKey: 'xxxxxx',
    authDomain: 'xxxxxx',
    databaseURL: 'xxxxxx',
    projectId: 'xxxxxx',
    storageBucket: 'xxxxxx',
    messagingSenderId: 'xxxxxx',
});

class ProtectedRoute extends Component {
    componentWillMount() {}

    render() {
        const { component: Component, layout: Layout, redirect, auth: isAuthorized, ...rest } = this.props;

        if (!this.props.hasOwnProperty('auth') && !this.props.hasOwnProperty('layout')) {
            return <Route {...this.props} />;
        }

        const template = Layout ? (
            <Layout>
                <Component />
            </Layout>
        ) : (
            <Component />
        );

        if (!this.props.hasOwnProperty('auth') && this.props.hasOwnProperty('layout')) {
            return <Route {...rest} component={() => template} />;
        }

        if (isAuthorized) {
            firebase.auth().onAuthStateChanged(user => {
                if(!user) {
                    console.log(user)
                    return redirect ? <Redirect to={{ pathname: redirect }} /> : <Route render={() => <div>Unauthorized</div>} />;
                }
            })
        }

        return <Route {...rest} render={() => template} />;
    }
}

export default ProtectedRoute;

我的路线是这样设置的,无论路线是否为私人,我都可以通过

import Route from './containers/ProtectedRoute';
 <Switch>
    <Route exact path="/" component={LandingPage} />
    <Route path="/private" auth={true} component={PrivatePage} />
    <Redirect to="/" />
  </Switch>

我希望发生的是,在访问/private时,我应该触发firebase.auth().onAuthStateChanged调用,然后在返回null时,我应该触发重定向逻辑。

相反,我仍然点击return <Route {...rest} render={() => template} />;

与此同时,firebase调用中的console.log输出null

1 个答案:

答案 0 :(得分:0)

firebase.auth().onAuthStateChanged是异步的,因此if (isAuthorized) { ... }内部的return语句永远不会运行。

您可以改为将此逻辑放入componentDidMount中,并将最新更改的结果存储在组件state中并使用。

示例

class ProtectedRoute extends Component {
  auth = firebase.auth();
  state = { user: this.auth.currentUser };

  componentDidMount() {
    this.unsubscribe = this.auth.onAuthStateChanged(user => {
      this.setState({ user });
    });
  }

  componentWillUnmount() {
    this.unsubscribe();
  }

  render() {
    const {
      component: Component,
      layout: Layout,
      redirect,
      auth: isAuthorized,
      ...rest
    } = this.props;
    const { user } = this.state;

    if (
      !this.props.hasOwnProperty("auth") &&
      !this.props.hasOwnProperty("layout")
    ) {
      return <Route {...this.props} />;
    }

    const template = Layout ? (
      <Layout>
        <Component />
      </Layout>
    ) : (
      <Component />
    );

    if (
      !this.props.hasOwnProperty("auth") &&
      this.props.hasOwnProperty("layout")
    ) {
      return <Route {...rest} component={() => template} />;
    }

    if (isAuthorized && !user) {
      return redirect ? (
        <Redirect to={{ pathname: redirect }} />
      ) : (
        <Route render={() => <div>Unauthorized</div>} />
      );
    }

    return <Route {...rest} render={() => template} />;
  }
}