React 定製私有路由

2021-09-13 21:49:47 字數 2566 閱讀 7837

需求,在非登入情況下不可以進入dashboard.js頁面

有src路徑下建立common資料夾下再建立乙個dashboard.js

期間用到了redux,所以也對應的把redux相關的檔案給貼出來

import react from 'react'

// 引入路由

import from 'react-router-dom';

import from 'react-redux';

import proptypes from 'prop-types';

// auth 傳的是否授權

const privateroute = () => (

/*** 呼叫rooter方法

* 它檢查使用者是否通過了身份驗證,

* 它呈現「元件」道具。如果沒有,它將重定向

* 使用者要/登入。

* */

(auth.isauthenticated === true

? : )

} />

)// 將狀態對映為屬性

const mapstatetoprops = (state) => ()

privateroute.prototype=

export default connect(mapstatetoprops)(privateroute)

rcs同級下reducers/index.js

/**

* 如果有多個reducer ,可以使用combinereducers方法將其合併,並暴露出去。

* 把combinereducers下定義的屬於傳入store.js

* */

import from 'redux'

// 對註冊驗證使用

import authreducer from './authreducer'

export default combinereducers()

rcs同級下reducers/authreducers.js

// 對authachtions.js返回回來的定義type型別進行判斷成功後再把使用者資料返回至元件

import from '../actions/types';

import isempty from '../validation/is-empty'

const initialstate =

}// reducer接受兩個引數,state,和action 作為引數,返回乙個新的state

export default function(state = initialstate,action)

default :

return state;}}

rcs同級下actions/authactions.js

// 使用者傳送請求的處理方法會在這裡執行

import axios from 'axios';

// 引入type型別

import from './types'

// 登入資訊

export const loginuser = (userdata) => dispatch => = res.data;

localstorage.setitem('jwtoken',token)

//設定axios的headers token

setauthtoken(token)

// 解析token

const decoded = jwt_decode(token)

// console.log(decoded)

// 解析之後用dispatch分發

dispatch(setcurrentuser(decoded))

}).catch(err =>)

})}export const setcurrentuser = decoded =>

}

rcs同級下actions/type.js

export const set_current_user ="set_current_user"
import react,  from 'react';

// 如果覺得 browserrouter 名字太長可以用 後面可以用router替代

// import from 'react-router-dom'

import from 'react-router-dom'

// provider元件,可以讓容器中所有的元件拿到state。

import from 'react-redux'

import store from './store';

// 引入私有路由

獲取Django所有路由

直接上 from django.urls import regexurlpattern defget all urls patterns,pre fix,is firt time false,result if is firt time result.clear for item in patter...

react 動態修改路由 React 動態路由

封裝乙個高階元件,用來實現將普通的元件轉換成動態元件import react from react const asynccomponent loadcomponent class asynccomponent extends react.component catch err this.state...

react學習六 react路由

react router 安裝包yarn add react router dom匯入路由模組 import reactdom from react dom route 表示乙個路由規則,在 route 上,有兩個比較重要的屬性,path component link 表示乙個路由的鏈結 就好比 v...