這次帶給大家react router4 redux控制路由權限步驟詳解,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 ( <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> <p> <Switch> <Route path="/login" component={Login} /> <Redirect from="/" exact to="/login"/>{/*注意redirect转向的地址要先定义好路由*/} <AuthorizedRoute path="/layout" component={Layout} /> <Route component={NoFound}/> </Switch> </p> </BrowserRouter> )
登入頁
就是把存在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.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,建立store,然後在需要使用redux的變數時候去connect一下redux,需要dispatch改變變數時,就直接把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 這裡的程式碼。感覺這份程式碼還挺不錯的,我一開始不會做就是看懂它才有點思路。
相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!
推薦閱讀:
vuex localstorage動態監聽storage步驟詳解
以上是react router4+redux控制路由權限步驟詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!