react router4+redux實現(xiàn)路由權(quán)限控制的方法
總體概述
一個完善的路由系統(tǒng)應(yīng)該是這樣子的,當(dāng)鏈接到的組件是需要登錄后才能查看,要能夠跳轉(zhuǎn)到登錄頁,然后登錄成功后又跳回來之前想訪問的頁面。這里主要是用一個權(quán)限控制類來定義路由路由信息,同時用redux把登錄成功后要訪問的路由地址給保存起來,登錄成功時看redux里面有沒有存地址,如果沒有存地址就跳轉(zhuǎn)到默認(rèn)路由地址。
路由權(quán)限控制類
在這個方法里面,通過sessionStorage判斷是否登錄了,如果沒有登錄,就保存一下當(dāng)前想要跳轉(zhuǎn)的路由到redux里面。然后跳轉(zhuǎn)到我們登錄頁。
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 (
<Route {...rest} render={props => {
return isLogged
? <Component {...props} />
: <Redirect to="/login" />
}} />
)
}
}
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 = () => (
<BrowserRouter>
<div>
<Switch>
<Route path="/login" component={Login} />
<Redirect from="/" exact to="/login"/>{/*注意redirect轉(zhuǎn)向的地址要先定義好路由*/}
<AuthorizedRoute path="/layout" component={Layout} />
<Route component={NoFound}/>
</Switch>
</div>
</BrowserRouter>
)
登錄頁
就是把存在redux里面的地址給取出來,登錄成功后就跳轉(zhuǎn)過去,如果沒有就跳轉(zhuǎn)到默認(rèn)頁面,我這里是默認(rèn)跳到主頁。因為用了antd的表單,代碼有點長,只需要看連接redux那兩句和handleSubmit里面的內(nèi)容。
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.isLogging = 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 === '' ? '/layout/home' : this.props.toPath
this.props.history.push(toPath);
})
}
});
}
render() {
const { getFieldDecorator } = this.props.form;
return (
<Form onSubmit={this.handleSubmit.bind(this)} className="login-form">
<FormItem>
{getFieldDecorator('userName', {
rules: [{ required: true, message: 'Please input your username!' }],
})(
<Input prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />} placeholder="Username" />
)}
</FormItem>
<FormItem>
{getFieldDecorator('password', {
rules: [{ required: true, message: 'Please input your Password!' }],
})(
<Input prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />} type="password" placeholder="Password" />
)}
</FormItem>
<FormItem>
{getFieldDecorator('remember', {
valuePropName: 'checked',
initialValue: true,
})(
<Checkbox>Remember me</Checkbox>
)}
<a className="login-form-forgot" href="">Forgot password</a>
<Button type="primary" htmlType="submit" className="login-form-button"
loading={this.isLogging ? true : false}>
{this.isLogging ? 'Loging' : 'Login'}
</Button>
Or <a href="">register now!</a>
</FormItem>
</Form>
);
}
}
const WrappedNormalLoginForm = Form.create()(NormalLoginForm);
const loginState = ({ loginState }) => ({
toPath: loginState.toPath
})
export default withRouter(connect(
loginState
)(WrappedNormalLoginForm))
順便說一下這里redux的使用吧。我暫時只會基本使用方法:定義reducer,定義actions,創(chuàng)建store,然后在需要使用redux的變量時候去connect一下redux,需要dispatch改變變量時,就直接把actions里面的方法引入,直接調(diào)用就可以啦。為了讓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
})
}
創(chuàng)建store
import { createStore, combineReducers } from 'redux'
import loginReducer from './reducer/loginReducer'
const reducers = combineReducers({
loginState: loginReducer //這里的屬性名loginState對應(yīng)于connect取出來的屬性名
})
const store = createStore(reducers)
export default store
差點忘記說了,路由控制類AuthorizedRoute參考了https://codepen.io/bradwestfall/project/editor/XWNWge?preview_height=50&open_file=src/app.js 這里的代碼。感覺這份代碼挺不錯的,我一開始不會做就是看懂它才有點思路。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React Hook 監(jiān)聽localStorage更新問題
這篇文章主要介紹了React Hook 監(jiān)聽localStorage更新問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-10-10
ReactNative短信驗證碼倒計時控件的實現(xiàn)代碼
本篇文章主要介紹了ReactNative短信驗證碼倒計時控件的實現(xiàn)代碼,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-07-07
Next.js實現(xiàn)react服務(wù)器端渲染的方法示例
這篇文章主要介紹了Next.js實現(xiàn)react服務(wù)器端渲染的方法示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01
使用React實現(xiàn)一個簡單的待辦事項列表的示例代碼
這篇文章我們將詳細(xì)講解如何建立一個這樣簡單的列表,文章通過代碼示例介紹的非常詳細(xì),對我們的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2023-08-08

