react的路由权限控制

在使用路由的时候,有的时候我们的界面只能够在登录之后才可以看的到,这个时候就需要使用路由权限控制了

找了资料发现一个就是我使用的方法,一个是高阶组件。 原谅菜鸟看不太懂不会使用高阶组件…………

首先在路由中做一个私有权限的限制,限制里面的path就是你的私有界面

router.js

 <Switch>
      <Route path="/" exact component={Home} />
      <PrivateRoute  path="/MyOptional"  component={MyOptional} />
      <Route render={() => <Redirect to="/" />} />
</Switch>

想要跳转到path的里面,首先在PrivateRoute里面做登录判断条件

private.js

import React from 'react';
import {Route,Redirect,withRouter} from 'react-router-dom';
import PropTypes from 'prop-types';
//私有路由,只有登录的用户才能访问
class PrivateRoute extends React.Component{
    componentWillMount(){
        let  isAuthenticated =  sessionStorage.getItem("userName") ? true :false;
        this.setState({isAuthenticated:isAuthenticated})
        if(!isAuthenticated){
            const {history} = this.props;
            setTimeout(() => {
                history.replace("/");
            }, 1000)
        }
    }
    render(){
        let { component: Component,path="/",exact=false,strict=false} = this.props;
        return this.state.isAuthenticated ?  (
            <Route  path={path} exact={exact}  strict={strict}  render={(props)=>( <Component {...props} /> )} />
        ) :  <Redirect
            to={{
                pathname: "/",
            }}    //这里必须使用redireact不能和上面一样使用<Route/>  因为会出现页面先跳转到myOption然后再跳转到首页的状况,这样用户体验不好
        /> ;
    }
}
PrivateRoute.propTypes  ={
    path:PropTypes.string.isRequired,
    exact:PropTypes.bool,
    strict:PropTypes.bool,
    component:PropTypes.func.isRequired
}
export default withRouter(PrivateRoute);

这样就ok了

注:因为我的登录界面是在首页或者各个界面的模态框,所以这里我的路径直接都是如果没有登录,直接跳转首页的。如果大家的登录界面是单独的,那可以直接跳转到登录界面了

还有个tips就是,如果你的界面没有在路由中进行声明,然后又想要在界面中使用route相关的路径参数,就可以引入withRouter,在this.props中得到了