在使用路由的时候,有的时候咱们的界面只可以在登陆以后才能够看的到,这个时候就须要使用路由权限控制了react
找了资料发现一个就是我使用的方法,一个是高阶组件。 原谅菜鸟看不太懂不会使用高阶组件…………session
首先在路由中作一个私有权限的限制,限制里面的path就是你的私有界面react-router
router.jsdom
<Switch> <Route path="/" exact component={Home} /> <PrivateRoute path="/MyOptional" component={MyOptional} /> <Route render={() => <Redirect to="/" />} /> </Switch>
想要跳转到path的里面,首先在PrivateRoute里面作登陆判断条件ui
private.jsthis
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了spa
注:由于个人登陆界面是在首页或者各个界面的模态框,因此这里个人路径直接都是若是没有登陆,直接跳转首页的。若是你们的登陆界面是单独的,那能够直接跳转到登陆界面了code
还有个tips就是,若是你的界面没有在路由中进行声明,而后又想要在界面中使用route相关的路径参数,就能够引入withRouter,在this.props中获得了component