【React.js 14】react-router4配合Redux實現(xiàn)多頁面應(yīng)用

上一篇中沾乘,我們寫的跳轉(zhuǎn)都是寫在index.js文件中,實際項目肯定不會是這樣的浑测,所以翅阵,這里,我們再來改寫一下案例迁央,做成多頁面切換的掷匠,用react-router4來實現(xiàn)。

首先岖圈,我們捋一捋思路:

  • 假設(shè)我們現(xiàn)在有兩個頁面:登錄頁面Auth.js 和 應(yīng)用內(nèi)頁Dashboard.js讹语;
  • 入口的index.js文件就要寫入兩個頁面的路由渲染模板;
  • Auth.js為第一個頁面蜂科,在頁面中判斷用戶是否登錄募强,已登錄株灸,直接RedirectDashboard.js,沒有登錄就直接渲染當(dāng)前頁面Auth.js即可
  • 對應(yīng)Auth.js使用的用戶信息擎值,登錄的交互事件慌烧,也以Redux進(jìn)行管理,單獨創(chuàng)建一個Auth.redux.js進(jìn)行管理鸠儿。
  • 應(yīng)用內(nèi)頁Dashboard.js則是之前的案例中就寫好的組件屹蚊,將其從index.js的渲染中剝離出來,單獨封裝成一個應(yīng)用內(nèi)頁进每。
  • 應(yīng)用內(nèi)頁Dashboard.js就包含了App.js組件汹粤,其num屬性、人員增減方法也是有一個index.redux.js文件在管理田晚。
  • 這時候嘱兼,會出現(xiàn)多個reducer,所以需要用combineReducer方法來用多個reducer去創(chuàng)建一個整體的reducer贤徒。
  • Auth.js依舊Auth.redux.js的用戶登錄信息進(jìn)行渲染頁面判斷芹壕,同時,也能通過Auth.redux.js的登錄動作去實現(xiàn)登錄跳轉(zhuǎn)接奈。
  • Dashboard.js則是根據(jù)Auth.redux.js的登出動作去實現(xiàn)登出跳轉(zhuǎn)踢涌。
思路差不多就是這樣,接下來就是動手寫代碼:

./scr路徑下創(chuàng)建Auth.js文件序宦,先簡單的寫下框架睁壁,作為登錄驗證的頁面:

import React, { Component } from 'react'

class Auth extends Component {
  render(){
    return(
      <div>
        <h2>當(dāng)前尚未登錄</h2>
        <p>點擊登錄</p>
      </div>
    )
  }
}

export default Auth



./scr路徑下創(chuàng)建Dashboard.js文件,把之前index.js文件內(nèi)的移到這里互捌,作為應(yīng)用內(nèi)的主頁面:

import React, { Component } from 'react'
import { Link ,Route} from 'react-router-dom'
import App from './App'

//定義兩個無狀態(tài)組件
function tecDep() {
  return <h2>技術(shù)部</h2>
}
function HRDep() {
  return <h2>人事部</h2>
}

class Dashboard extends Component {
  render(){
    return(
      <div>
        {/* 指定路由跳轉(zhuǎn)的導(dǎo)航 */}
        <ul>
          <li>
            <Link to='/dashboard'>總部</Link>
          </li>
          <li>
            <Link to='/dashboard/tecDep'>技術(shù)部</Link>
          </li>
          <li>
            <Link to='/dashboard/HRDep'>人事部</Link>
          </li>
        </ul>
        <Route path='/dashboard' exact component={App}></Route>
        <Route path='/dashboard/tecDep' component={tecDep}></Route>
        <Route path='/dashboard/HRDep' component={HRDep}></Route>
      </div>
    )
  }
}

export default Dashboard



修改index.js的渲染部分潘明,因為index.js屬于入口,只要套每個功能頁面的最頂層秕噪,修改成:

//引入新創(chuàng)建的兩個頁面組件
import Auth from './Auth'
import Dashboard from './Dashboard'
.
.
.
//render修改一下
ReactDom.render(
  <Provider store={store}>
    <BrowserRouter>
      <Switch>
        {/* 路由的渲染模板钉疫,渲染哪個路由,就寫哪個路徑 */}
        <Route path='/login' component={Auth}></Route>
        <Route path='/dashboard' component={Dashboard}></Route>
        <Redirect to='/HRDep'></Redirect>
      </Switch>
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
)


到這一步巢价,我們手動在瀏覽器地址欄輸入http://localhost:3000/dashboardhttp://localhost:3000/login就能看到頁面了牲阁。接下來開始處理數(shù)據(jù)的操作以及事件的執(zhí)行。



針對Auth.js的用戶信息和登錄事件壤躲,都用react-redux來處理城菊,在./src目錄下創(chuàng)建Auth.redux.js文件:

//管理登錄驗證相關(guān)的信息和事件
const LOGIN = 'login'
const LOGOUT = 'logout'

export function authReducer(state = {isAuth:false,userName:'Mike'},action){
  switch (action.type) {
    case LOGIN:
      return {...state,isAuth:true}
    case LOGOUT:
      return {...state,isAuth:false}
    default:
      return state
  }
}

export function loginAction() {
  return {type:LOGIN}
}
export function logoutAction() {
  return {type:LOGOUT}
}



Auth.js內(nèi)部要取對應(yīng)的值和事件,但是碉克,index.js里面使用的是manageCompany來創(chuàng)建的store凌唬,怎么把Auth.redux.jsreducer也放進(jìn)去呢,這就需要用到combineReducers方法來生成一個整體漏麦,我們在./src目錄下創(chuàng)建Reducer.js文件:

//把引入的reducer整合成一個傳出去
import { combineReducers } from 'redux'
import { manageCompany } from './index.redux'
import { authReducer } from './Auth.redux'

export default combineReducers({manageCompany ,authReducer})

index.js中也改寫下:

import Reducers from './Reducer'
.
.
.
const store = createStore(Reducers, compose(
    applyMiddleware(thunk),
    reduxDevtools
))



有了新的store之后客税,就可以開始為登錄頁面Auth.js寫登錄邏輯了:

import React, { Component } from 'react'
//引入react-redux所需的庫况褪、reducer中的登錄事件、登錄后頁面重定向的庫
import { connect } from 'react-redux'
import { loginAction } from './Auth.redux'
import { Redirect } from 'react-router-dom'
//自動連接redux
@connect(
  state=>state.authReducer,
  { loginAction }
)
class Auth extends Component {
  render(){
    return(
      <div>
        //根據(jù)用戶的狀態(tài)更耻,判斷是否要重定向测垛,登錄后因為會刷新渲染,也會走一次判斷
        {this.props.isAuth ? <Redirect to='/dashboard'></Redirect> : null}
        <h2>當(dāng)前尚未登錄</h2>
        <p onClick={this.props.loginAction}>點擊登錄</p>
      </div>
    )
  }
}
export default Auth

但是此時會報錯:

錯誤

因為兩處connect的地方傳入的state類型無法自動對應(yīng)上秧均,這里我們就要自己動手去修改了食侮,問題出來./scr/App.js中,把connect的地方修改為:

@connect((state)=>{
  //需要哪些狀態(tài)數(shù)據(jù)
  return {num : state.manageCompany}
} ,{ hire, hireAsync ,fire })



到此目胡,登錄已經(jīng)實現(xiàn)了锯七。
Dashboard.js也要實現(xiàn)一個登出的功能:

//引入`connect`、`logoutAction`
import { connect } from 'react-redux'
import { logoutAction } from './Auth.redux'
.
.
.
@connect(
  state=>state.authReducer,
  { logoutAction }
)
class Dashboard extends Component {
  render(){
    const match = this.props.match
    const redirectToLogin = <Redirect to='/login'></Redirect>
    const app = (
      <div>
        {/* 指定路由跳轉(zhuǎn)的導(dǎo)航 */}
        <ul>
          <li>
            <Link to={`${match.url}`}>總部</Link>
          </li>
          <li>
            <Link to={`${match.url}/tecDep`}>技術(shù)部</Link>
          </li>
          <li>
            <Link to={`${match.url}/HRDep`}>人事部</Link>
          </li>
        </ul>
        <Route path={`${match.url}`} exact component={App}></Route>
        <Route path={`${match.url}/tecDep`} component={tecDep}></Route>
        <Route path={`${match.url}/HRDep`} component={HRDep}></Route>
        {this.props.isAuth ?<p onClick={this.props.logoutAction}>登出</p> : null}
      </div>
    )
    return(
      this.props.isAuth ? app :redirectToLogin
    )
  }
}

至此已經(jīng)實現(xiàn)了頁面登錄登出的切換效果誉己。



上代碼:
App.js

import React , { Component } from 'react'
import { connect } from 'react-redux'
import { hire, hireAsync ,fire } from './index.redux'

//狀態(tài)映射屬性
@connect((state)=>{
  //需要哪些狀態(tài)數(shù)據(jù)
  return {num : state.manageCompany}
} ,{ hire, hireAsync ,fire })
class App extends Component {
  render() {
    return (
      <div>
        <h1>公司現(xiàn)在有{this.props.num}人</h1>
        <p onClick={this.props.hire}>雇傭一人</p>
        <p onClick={this.props.hireAsync}>雇傭一人,晚兩天到</p>
        <p onClick={this.props.fire}>開除一人</p>
      </div>
    )
  }
}
export default App



Auth.js

//登錄驗證頁面
import React, { Component } from 'react'
import { connect } from 'react-redux'
import { loginAction } from './Auth.redux'
import { Redirect } from 'react-router-dom'
@connect(
  state=>state.authReducer,
  { loginAction }
)
class Auth extends Component {
  render(){
    return(
      <div>
        {this.props.isAuth ? <Redirect to='/dashboard'></Redirect> : null}
        <h2>當(dāng)前尚未登錄</h2>
        <p onClick={this.props.loginAction}>點擊登錄</p>
      </div>
    )
  }
}
export default Auth



Auth.redux.js

//管理登錄驗證相關(guān)的信息和事件
const LOGIN = 'login'
const LOGOUT = 'logout'

export function authReducer(state = {isAuth:false,userName:'Mike'},action){
  switch (action.type) {
    case LOGIN:
      return {...state,isAuth:true}
    case LOGOUT:
      return {...state,isAuth:false}
    default:
      return state
  }
}
export function loginAction() {
  return {type:LOGIN}
}
export function logoutAction() {
  return {type:LOGOUT}
}



Dashboard.js

import React, { Component } from 'react'
import { Link ,Route ,Redirect} from 'react-router-dom'
import App from './App'
import { connect } from 'react-redux'
import { logoutAction } from './Auth.redux'

//定義兩個無狀態(tài)組件
function tecDep() {
  return <h2>技術(shù)部</h2>
}
function HRDep() {
  return <h2>人事部</h2>
}
@connect(
  state=>state.authReducer,
  { logoutAction }
)
class Dashboard extends Component {
  render(){
    const match = this.props.match
    const redirectToLogin = <Redirect to='/login'></Redirect>
    const app = (
      <div>
        {/* 指定路由跳轉(zhuǎn)的導(dǎo)航 */}
        <ul>
          <li>
            <Link to={`${match.url}`}>總部</Link>
          </li>
          <li>
            <Link to={`${match.url}/tecDep`}>技術(shù)部</Link>
          </li>
          <li>
            <Link to={`${match.url}/HRDep`}>人事部</Link>
          </li>
        </ul>
        <Route path={`${match.url}`} exact component={App}></Route>
        <Route path={`${match.url}/tecDep`} component={tecDep}></Route>
        <Route path={`${match.url}/HRDep`} component={HRDep}></Route>
        {this.props.isAuth ?<p onClick={this.props.logoutAction}>登出</p> : null}
      </div>
    )
    return(
      this.props.isAuth ? app :redirectToLogin
    )
  }
}
export default Dashboard



index.js

import React from 'react'
import ReactDom from 'react-dom'
import { createStore ,applyMiddleware ,compose} from 'redux'
import thunk from 'redux-thunk'
import { Provider } from 'react-redux'
import Reducers from './Reducer'
import { BrowserRouter, Route ,Redirect ,Switch} from 'react-router-dom'
import Auth from './Auth'
import Dashboard from './Dashboard'

const reduxDevtools = window.devToolsExtension ? window.devToolsExtension() : ()=>{}
// 通過reducer創(chuàng)建store眉尸,通過compose把幾個函數(shù)組合起來
const store = createStore(Reducers, compose(
    applyMiddleware(thunk),
    reduxDevtools
))

ReactDom.render(
  <Provider store={store}>
    <BrowserRouter>
      <Switch>
        {/* 路由的渲染模板,渲染哪個路由巨双,就寫哪個路徑 */}
        <Route path='/login' component={Auth}></Route>
        <Route path='/dashboard' component={Dashboard}></Route>
        <Redirect to='/dashboard'></Redirect>
      </Switch>
    </BrowserRouter>
  </Provider>,
  document.getElementById('root')
)



index.redux.js

// 定義成常量噪猾,盡量避免使用魔法值
const HIRE = 'hireEmployee'
const FIRE = 'fireEmployee'

// 導(dǎo)出并且定義reducer
export function manageCompany(total = 1, action) {
  switch (action.type) {
    case HIRE:
      return total + 1;
    case FIRE:
      return total - 1;
    default:
      return 1;
  }
}

// type為HIRE的action
export function hire() {
  return {type : HIRE}
}
// type為HIRE的異步action
export function hireAsync() {
  return dispatch=>{
    setTimeout(()=>{
      dispatch(hire())
    },2000)
  }
}
// type為FIRE的action
export function fire() {
  return {type : FIRE}
}



Reducer.js

import { combineReducers } from 'redux'
import { manageCompany } from './index.redux'
import { authReducer } from './Auth.redux'

export default combineReducers({manageCompany ,authReducer})

Done!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市炉峰,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌脉执,老刑警劉巖疼阔,帶你破解...
    沈念sama閱讀 219,039評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異半夷,居然都是意外死亡婆廊,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評論 3 395
  • 文/潘曉璐 我一進(jìn)店門巫橄,熙熙樓的掌柜王于貴愁眉苦臉地迎上來淘邻,“玉大人,你說我怎么就攤上這事湘换”鼍耍” “怎么了?”我有些...
    開封第一講書人閱讀 165,417評論 0 356
  • 文/不壞的土叔 我叫張陵彩倚,是天一觀的道長筹我。 經(jīng)常有香客問我,道長帆离,這世上最難降的妖魔是什么蔬蕊? 我笑而不...
    開封第一講書人閱讀 58,868評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮哥谷,結(jié)果婚禮上岸夯,老公的妹妹穿的比我還像新娘麻献。我一直安慰自己,他們只是感情好猜扮,可當(dāng)我...
    茶點故事閱讀 67,892評論 6 392
  • 文/花漫 我一把揭開白布勉吻。 她就那樣靜靜地躺著,像睡著了一般破镰。 火紅的嫁衣襯著肌膚如雪餐曼。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,692評論 1 305
  • 那天鲜漩,我揣著相機(jī)與錄音源譬,去河邊找鬼。 笑死孕似,一個胖子當(dāng)著我的面吹牛踩娘,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播喉祭,決...
    沈念sama閱讀 40,416評論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼养渴,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了泛烙?” 一聲冷哼從身側(cè)響起理卑,我...
    開封第一講書人閱讀 39,326評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎蔽氨,沒想到半個月后藐唠,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,782評論 1 316
  • 正文 獨居荒郊野嶺守林人離奇死亡鹉究,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,957評論 3 337
  • 正文 我和宋清朗相戀三年宇立,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片自赔。...
    茶點故事閱讀 40,102評論 1 350
  • 序言:一個原本活蹦亂跳的男人離奇死亡妈嘹,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出绍妨,到底是詐尸還是另有隱情润脸,我是刑警寧澤,帶...
    沈念sama閱讀 35,790評論 5 346
  • 正文 年R本政府宣布他去,位于F島的核電站津函,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏孤页。R本人自食惡果不足惜尔苦,卻給世界環(huán)境...
    茶點故事閱讀 41,442評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧允坚,春花似錦魂那、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至展运,卻和暖如春活逆,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背拗胜。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評論 1 272
  • 我被黑心中介騙來泰國打工蔗候, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人埂软。 一個月前我還...
    沈念sama閱讀 48,332評論 3 373
  • 正文 我出身青樓锈遥,卻偏偏與公主長得像,于是被迫代替她去往敵國和親勘畔。 傳聞我的和親對象是個殘疾皇子所灸,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,044評論 2 355

推薦閱讀更多精彩內(nèi)容