react router4+redux实现路由权限控制的方法

网友投稿 428 2023-02-06


react router4+redux实现路由权限控制的方法

总体概述

一个完善的路由系统应该是这样子的,当链接到的组件是需要登录后才能查看,要能够跳转到登录页,然后登录成功后又跳回来之前想访问的页面。这里主要是用一个权限控制类来定义路由路由信息,同时用redux把登录成功后要访问的路由地址给保存起来,登录成功时看redux里面有没有存地址,如果没有存地址就跳转到默认路由地址。

路由权限控制类

在这个方法里面,通过sessionStorage判断是否登录了,如果没有登录,就保存一下当前想要跳转的路由到redux里面。然后跳转到我们登录页。

import React from 'react'

import { Route, Redirect } from 'react-router-dom'

import { setLoginRedirectUrl } from '../actions/loginAction'

class AuthorizedRoute extends React.Component {

render() {

const { component: Component, ...rest } = this.props

const isLogged = sessionStorage.getItem("userName") != null ? true : false;

if(!isLogged) {

setLoginRedirectUrl(this.props.location.pathname);

}

return (

{

return isLogged

?

:

}} />

)

}

}

export default AuthorizedRoute

路由定义信息

路由信息也很简单。只是对需要登录后才能查看的路由用AuthorizedRoute定义。

import React from 'react'

import { BrowserRouter, Switch, Route, Redirect } from 'react-router-dom'

import Layout from '../pages/layout/Layout'

import Login from '../pages/login/Login'

import AuthorizedRoute from './AuthorizedRoute'

import NoFound from '../pages/noFound/NoFound'

import Home from '../pages/home/Home'

import Order from '../pages/Order/Order'

import WorkOrder from '../pages/Order/WorkOrder'

export const Router = () => (

{/*注意redirect转向的地址要先定义好路由*/}

)

登录页

就是把存在redux里面的地址给取出来,登录成功后就跳转过去,如果没有就跳转到默认页面,我这里是默认跳到主页。因为用了antd的表单,代码有点长,只需要看连接redux那两句和handleSubmit里面的内容。

import React from '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'

const FormItem = Form.Item;

class NormalLoginForm extends React.Component {

constructor(props) {

super(props);

this.isLoggihttp://ng = false;

}

handleSubmit = (e) => {

e.preventDefault();

this.props.form.validateFields((err, values) => {

if (!err) {

this.isLogging = true;

login(values).then(() => {

this.isLogging = false;

let toPath = this.props.toPath === '' ? '/layouthttp:///home' : this.props.toPath

this.props.history.push(toPath);

})

}

});

}

render() {

const { getFieldDecorator } = this.props.form;

return (

{getFieldDecorator('userName', {

rules: [{ required: true, message: 'Please input your username!' }],

})(

} placeholder="Username" />

)}

{getFieldDecorator('password', {

rules: [{ required: true, message: 'Please input your Password!' }],

})(

} type="password" placeholder="Password" />

)}

{getFieldDecorator('remember', {

valuePropName: 'checked',

initialValue: true,

})(

Remember me

)}

Forgot password

loading={this.isLogging ? true : false}>

{this.isLogging ? 'Loging' : 'Login'}

Or register now!

);

}

}

const WrappedNormalLoginForm = Form.create()(NormalLoginForm);

const loginState = ({ loginState }) => ({

toPath: loginState.toPath

})

export default withRouter(connect(

loginState

)(WrappedNormalLoginForm))

顺便说一下这里redux的使用吧。我暂时只会基本使用方法:定义reducer,定义actions,创建store,然后在需要使用redux的变量时候去connect一下redux,需要dispatch改变变量时,就http://直接把actions里面的方法引入,直接调用就可以啦。为了让actions和reducer里面的事件名称对的上,怕打错字和便于后面修改吧,我建了个actionsEvent.js来存放事件名称。

reducer:

import * as ActionEvent from '../constants/actionsEvent'

const initialState = {

toPath: ''

}

const loginRedirectPath = (state = initialState, action) => {

if(action.type === ActionEvent.Login_Redirect_Event) {

return Object.assign({}, state, {

toPath: action.toPath

})

}

return state;

}

export default loginRedirectPath

actions:

import store from '../store'

import * as ActionEvent from '../constants/actionsEvent'

export const setLoginRedirectUrl = (toPath) => {

return store.dispatch({

type: ActionEvent.Login_Redirect_Event,

toPath: toPath

})

}

创建store

import { createStore, combineReducers } from 'redux'

import loginReducer from './reducer/loginReducer'

const reducers = combineReducers({

loginState: loginReducer //这里的属性名loginState对应于connect取出来的属性名

})

const store = createStore(reducers)

export default store

差点忘记说了,路由控制类AuthorizedRoute参考了https://codepen.io/bradwestfall/project/editor/XWNWge?preview_height=50&open_file=src/app.js 这里的代码。感觉这份代码挺不错的,我一开始不会做就是看懂它才有点思路。


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:Vue SSR 组件加载问题
下一篇:Struts2学习教程之输入校验示例详解
相关文章

 发表评论

暂时没有评论,来抢沙发吧~