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';
//私有路由,只有登录的⽤户才能访问
react router6class PrivateRoute extends React.Component{
componentWillMount(){
let  isAuthenticated =  Item("userName") ? true :false;
this.setState({isAuthenticated:isAuthenticated})
if(!isAuthenticated){
const {history} = this.props;
setTimeout(() => {
}, 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中得到了