我正在尝试使用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
答案 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} />;
}
}