react router4+redux实现路由权限控制的方法
总体概述
一个完善的路由系统应该是这样子的,当链接到的组件是需要登录后才能查看,要能够跳转到登录页,然后登录成功后又跳回来之前想访问的页面。这里主要是用一个权限控制类来定义路由路由信息,同时用redux把登录成功后要访问的路由地址给保存起来,登录成功时看redux里面有没有存地址,如果没有存地址就跳转到默认路由地址。
路由权限控制类
在这个方法里面,通过sessionStorage判断是否登录了,如果没有登录,就保存一下当前想要跳转的路由到redux里面。然后跳转到我们登录页。
importReactfrom'react'
import{Route,Redirect}from'react-router-dom'
import{setLoginRedirectUrl}from'../actions/loginAction'
classAuthorizedRouteextendsReact.Component{
render(){
const{component:Component,...rest}=this.props
constisLogged=sessionStorage.getItem("userName")!=null?true:false;
if(!isLogged){
setLoginRedirectUrl(this.props.location.pathname);
}
return(
{
returnisLogged
?
:
}}/>
)
}
}
exportdefaultAuthorizedRoute
路由定义信息
路由信息也很简单。只是对需要登录后才能查看的路由用AuthorizedRoute定义。
importReactfrom'react'
import{BrowserRouter,Switch,Route,Redirect}from'react-router-dom'
importLayoutfrom'../pages/layout/Layout'
importLoginfrom'../pages/login/Login'
importAuthorizedRoutefrom'./AuthorizedRoute'
importNoFoundfrom'../pages/noFound/NoFound'
importHomefrom'../pages/home/Home'
importOrderfrom'../pages/Order/Order'
importWorkOrderfrom'../pages/Order/WorkOrder'
exportconstRouter=()=>(
{/*注意redirect转向的地址要先定义好路由*/}
)
登录页
就是把存在redux里面的地址给取出来,登录成功后就跳转过去,如果没有就跳转到默认页面,我这里是默认跳到主页。因为用了antd的表单,代码有点长,只需要看连接redux那两句和handleSubmit里面的内容。
importReactfrom'react'
import'./Login.css'
import{login}from'../../mock/mock'
import{Form,Icon,Input,Button,Checkbox}from'antd';
import{withRouter}from'react-router-dom';
import{connect}from'react-redux'
constFormItem=Form.Item;
classNormalLoginFormextendsReact.Component{
constructor(props){
super(props);
this.isLogging=false;
}
handleSubmit=(e)=>{
e.preventDefault();
this.props.form.validateFields((err,values)=>{
if(!err){
this.isLogging=true;
login(values).then(()=>{
this.isLogging=false;
lettoPath=this.props.toPath===''?'/layout/home':this.props.toPath
this.props.history.push(toPath);
})
}
});
}
render(){
const{getFieldDecorator}=this.props.form;
return(
{getFieldDecorator('userName',{
rules:[{required:true,message:'Pleaseinputyourusername!'}],
})(
}placeholder="Username"/>
)}
{getFieldDecorator('password',{
rules:[{required:true,message:'PleaseinputyourPassword!'}],
})(
}type="password"placeholder="Password"/>
)}
{getFieldDecorator('remember',{
valuePropName:'checked',
initialValue:true,
})(
Rememberme
)}
Forgotpassword
{this.isLogging?'Loging':'Login'}
Orregisternow!
);
}
}
constWrappedNormalLoginForm=Form.create()(NormalLoginForm);
constloginState=({loginState})=>({
toPath:loginState.toPath
})
exportdefaultwithRouter(connect(
loginState
)(WrappedNormalLoginForm))
顺便说一下这里redux的使用吧。我暂时只会基本使用方法:定义reducer,定义actions,创建store,然后在需要使用redux的变量时候去connect一下redux,需要dispatch改变变量时,就直接把actions里面的方法引入,直接调用就可以啦。为了让actions和reducer里面的事件名称对的上,怕打错字和便于后面修改吧,我建了个actionsEvent.js来存放事件名称。
reducer:
import*asActionEventfrom'../constants/actionsEvent'
constinitialState={
toPath:''
}
constloginRedirectPath=(state=initialState,action)=>{
if(action.type===ActionEvent.Login_Redirect_Event){
returnObject.assign({},state,{
toPath:action.toPath
})
}
returnstate;
}
exportdefaultloginRedirectPath
actions:
importstorefrom'../store'
import*asActionEventfrom'../constants/actionsEvent'
exportconstsetLoginRedirectUrl=(toPath)=>{
returnstore.dispatch({
type:ActionEvent.Login_Redirect_Event,
toPath:toPath
})
}
创建store
import{createStore,combineReducers}from'redux'
importloginReducerfrom'./reducer/loginReducer'
constreducers=combineReducers({
loginState:loginReducer//这里的属性名loginState对应于connect取出来的属性名
})
conststore=createStore(reducers)
exportdefaultstore
差点忘记说了,路由控制类AuthorizedRoute参考了https://codepen.io/bradwestfall/project/editor/XWNWge?preview_height=50&open_file=src/app.js这里的代码。感觉这份代码挺不错的,我一开始不会做就是看懂它才有点思路。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。