最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

react router4+redux實現(xiàn)路由權限控制的方法

 更新時間:2018年05月03日 09:30:43   作者:supportlss  
本篇文章主要介紹了react router4+redux實現(xiàn)路由權限控制的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

總體概述

一個完善的路由系統(tǒng)應該是這樣子的,當鏈接到的組件是需要登錄后才能查看,要能夠跳轉到登錄頁,然后登錄成功后又跳回來之前想訪問的頁面。這里主要是用一個權限控制類來定義路由路由信息,同時用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>
      <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里面的內(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里面的方法引入,直接調用就可以啦。為了讓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對應于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)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關文章

  • React中設置樣式style方式

    React中設置樣式style方式

    這篇文章主要介紹了React中設置樣式style方式,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-11-11
  • 基于React實現(xiàn)虛擬滾動的方案詳解

    基于React實現(xiàn)虛擬滾動的方案詳解

    這篇文章將以固定高度和非固定高度兩種場景展開React中虛擬滾動的實現(xiàn),文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下
    2025-03-03
  • React?Flux與Redux設計及使用原理

    React?Flux與Redux設計及使用原理

    這篇文章主要介紹了React?Flux與Redux設計及使用,Redux最主要是用作應用狀態(tài)的管理。簡言之,Redux用一個單獨的常量狀態(tài)樹(state對象)保存這一整個應用的狀態(tài),這個對象不能直接被改變
    2023-03-03
  • React實現(xiàn)二級聯(lián)動的方法

    React實現(xiàn)二級聯(lián)動的方法

    這篇文章主要為大家詳細介紹了React實現(xiàn)二級聯(lián)動的方法,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • 聊聊jenkins部署vue/react項目的問題

    聊聊jenkins部署vue/react項目的問題

    本文給大家介紹了jenkins部署vue/react項目的問題,文末給大家提到了centOS安裝jenkins的腳本,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2022-02-02
  • React 高階組件入門介紹

    React 高階組件入門介紹

    本篇文章主要介紹了React高階組件入門介紹,這篇文章中我們詳細的介紹了什么是高階組件,如何使用高階組件,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01
  • React組件重構之嵌套+繼承及高階組件詳解

    React組件重構之嵌套+繼承及高階組件詳解

    這篇文章主要給大家介紹了關于React組件重構之嵌套+繼承及高階組件的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2018-07-07
  • 關于React Native報Cannot initialize a parameter of type''NSArray<id<RCTBridgeModule>>錯誤(解決方案)

    關于React Native報Cannot initialize a parameter of type''NSArra

    這篇文章主要介紹了關于React Native報Cannot initialize a parameter of type'NSArray<id<RCTBridgeModule>>錯誤,本文給大家分享解決方案,需要的朋友可以參考下
    2021-05-05
  • 使用ReactJS實現(xiàn)tab頁切換、菜單欄切換、手風琴切換和進度條效果

    使用ReactJS實現(xiàn)tab頁切換、菜單欄切換、手風琴切換和進度條效果

    這篇文章主要介紹了使用ReactJS實現(xiàn)tab頁切換、菜單欄切換、手風琴切換和進度條效果的相關資料,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下
    2016-10-10
  • 解決React報錯Expected?`onClick`?listener?to?be?a?function

    解決React報錯Expected?`onClick`?listener?to?be?a?function

    這篇文章主要為大家介紹了React報錯Expected?`onClick`?listener?to?be?a?function解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-12-12

最新評論

中超| 新干县| 惠来县| 株洲县| 肇源县| 永州市| 西畴县| 河间市| 尚义县| 云林县| 健康| 高碑店市| 梅河口市| 赤峰市| 涞水县| 藁城市| 密云县| 永和县| 开远市| 上高县| 大安市| 正宁县| 蓬莱市| 营口市| 红河县| 乳山市| 延寿县| 民乐县| 平远县| 社旗县| 彩票| 南雄市| 柏乡县| 常宁市| 疏附县| 曲阜市| 涿鹿县| 鹰潭市| 青川县| 卓尼县| 武平县|