如何将authguard应用于reactjs中具有多个组件的路由

时间:2018-03-29 09:42:01

标签: reactjs

我有单个和多个组件的路由。我使用authguard来限制对某些路由的访问。如何将authguard应用于具有多个组件的路由。

routes.js

import { BrowserRouter as Router,Route} from 'react-router-dom';
import React from 'react';
import { FirstConnectedComponent,SecondConnectedComponent } from './App.js';
import Header  from './components/header.js';
import Footer  from './components/footer.js';
import Login from './components/login.js';
import UserReg from './components/registration.js';
import Home from './components/home';
import requireAuth from './components/authentication';
import PrivateRoute from './components/privateroutes';
const routes=() => (
    <Router>
        <div>
            <Header />
                <Route exact path="/" render={ props =>  <div><FirstConnectedComponent /><SecondConnectedComponent /></div>} />
                <Route path="/login" component={PrivateRoute(Login) } />
                <Route path="/register" component={ UserReg } />
                <Route path="/home" component={ requireAuth(Home)} />
            <Footer />
        </div>
    </Router>

)
export default routes;

在上面的代码中,我已经将authguard应用于具有单个组件的路由。但我不知道如何应用于具有多个组件的路由。

privateroute

import { connect } from 'react-redux';
import React from 'react';
import { withRouter } from 'react-router';

export default function PrivateRoute(Component) {

  class AuthenticatedComponent extends React.Component {

    componentWillMount() {
        console.log(this.props.loginStatus);
      this.checkAuth();
    }

    checkAuth() {
       if (this.props.loginStatus==1) {
        this.props.history.push(`/home`);
      }
    }

    render() {
      return this.props.loginStatus!=1
        ? <Component { ...this.props } />
        : null;
    }

  }
  function mapStateProps(state)  {
    return {
        loginStatus:state.loginDetails.status
    }   
  }
  return connect(mapStateProps)(withRouter(AuthenticatedComponent));
}

1 个答案:

答案 0 :(得分:1)

使用render道具而不是使用component道具,因为您在PrivateRoute中使用了PrivateRoute道具,并将渲染函数与const routes=() => ( <Router> <div> <Header /> <Route exact path="/" component={PrivateRoute(props => <div><FirstConnectedComponent /><SecondConnectedComponent /></div>)} /> <Route path="/login" component={PrivateRoute(Login) } /> <Route path="/register" component={ UserReg } /> <Route path="/home" component={ requireAuth(Home)} /> <Footer /> </div> </Router> ) HOC包装在一起,如

var imgs = {
    a: function(){
        //...
    },
    b: function(){
        //...
    },
    c: function(){
        //...
    }
};
var preloadImgs = function(){
    imgs.a();
    imgs.b();
    imgs.c();
};
preloadImgs();