一個完善的路由系統應該是這樣子的,當連接到的組件是須要登陸後才能查看,要可以跳轉到登陸頁,而後登陸成功後又跳回來以前想訪問的頁面。這裏主要是用一個權限控制類來定義路由路由信息,同時用redux把登陸成功後要訪問的路由地址給保存起來,登陸成功時看redux裏面有沒有存地址,若是沒有存地址就跳轉到默認路由地址。css
在這個方法裏面,經過sessionStorage判斷是否登陸了,若是沒有登陸,就保存一下當前想要跳轉的路由到redux裏面。而後跳轉到咱們登陸頁。html
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定義。react
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轉向的地址要先定義好路由*/} <AuthorizedRoute path="/layout" component={Layout} /> <Route component={NoFound}/> </Switch> </div> </BrowserRouter> )
就是把存在redux裏面的地址給取出來,登陸成功後就跳轉過去,若是沒有就跳轉到默認頁面,我這裏是默認跳到主頁。由於用了antd的表單,代碼有點長,只須要看鏈接redux那兩句和handleSubmit裏面的內容。redux
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:session
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:antd
import store from '../store' import * as ActionEvent from '../constants/actionsEvent' export const setLoginRedirectUrl = (toPath) => { return store.dispatch({ type: ActionEvent.Login_Redirect_Event, toPath: toPath }) }
建立storereact-router
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/bradwestfa... 這裏的代碼。感受這份代碼挺不錯的,我一開始不會作就是看懂它纔有點思路。app