美文网首页我爱编程
【React.js 14】react-router4配合Redu

【React.js 14】react-router4配合Redu

作者: IUVO | 来源:发表于2018-04-02 21:21 被阅读2861次

上一篇中,我们写的跳转都是写在index.js文件中,实际项目肯定不会是这样的,所以,这里,我们再来改写一下案例,做成多页面切换的,用react-router4来实现。

首先,我们捋一捋思路:

  • 假设我们现在有两个页面:登录页面Auth.js 和 应用内页Dashboard.js
  • 入口的index.js文件就要写入两个页面的路由渲染模板;
  • Auth.js为第一个页面,在页面中判断用户是否登录,已登录,直接RedirectDashboard.js,没有登录就直接渲染当前页面Auth.js即可
  • 对应Auth.js使用的用户信息,登录的交互事件,也以Redux进行管理,单独创建一个Auth.redux.js进行管理。
  • 应用内页Dashboard.js则是之前的案例中就写好的组件,将其从index.js的渲染中剥离出来,单独封装成一个应用内页。
  • 应用内页Dashboard.js就包含了App.js组件,其num属性、人员增减方法也是有一个index.redux.js文件在管理。
  • 这时候,会出现多个reducer,所以需要用combineReducer方法来用多个reducer去创建一个整体的reducer
  • Auth.js依旧Auth.redux.js的用户登录信息进行渲染页面判断,同时,也能通过Auth.redux.js的登录动作去实现登录跳转。
  • Dashboard.js则是根据Auth.redux.js的登出动作去实现登出跳转。
思路差不多就是这样,接下来就是动手写代码:

./scr路径下创建Auth.js文件,先简单的写下框架,作为登录验证的页面:

import React, { Component } from 'react'

class Auth extends Component {
  render(){
    return(
      <div>
        <h2>当前尚未登录</h2>
        <p>点击登录</p>
      </div>
    )
  }
}

export default Auth


./scr路径下创建Dashboard.js文件,把之前index.js文件内的移到这里,作为应用内的主页面:
import React, { Component } from 'react'
import { Link ,Route} from 'react-router-dom'
import App from './App'

//定义两个无状态组件
function tecDep() {
  return <h2>技术部</h2>
}
function HRDep() {
  return <h2>人事部</h2>
}

class Dashboard extends Component {
  render(){
    return(
      <div>
        {/* 指定路由跳转的导航 */}
        <ul>
          <li>
            <Link to='/dashboard'>总部</Link>
          </li>
          <li>
            <Link to='/dashboard/tecDep'>技术部</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属于入口,只要套每个功能页面的最顶层,修改成:
//引入新创建的两个页面组件
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就能看到页面了。接下来开始处理数据的操作以及事件的执行。



针对Auth.js的用户信息和登录事件,都用react-redux来处理,在./src目录下创建Auth.redux.js文件:
//管理登录验证相关的信息和事件
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内部要取对应的值和事件,但是,index.js里面使用的是manageCompany来创建的store,怎么把Auth.redux.jsreducer也放进去呢,这就需要用到combineReducers方法来生成一个整体,我们在./src目录下创建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>
        //根据用户的状态,判断是否要重定向,登录后因为会刷新渲染,也会走一次判断
        {this.props.isAuth ? <Redirect to='/dashboard'></Redirect> : null}
        <h2>当前尚未登录</h2>
        <p onClick={this.props.loginAction}>点击登录</p>
      </div>
    )
  }
}
export default Auth

但是此时会报错:

错误
因为两处connect的地方传入的state类型无法自动对应上,这里我们就要自己动手去修改了,问题出来./scr/App.js中,把connect的地方修改为:
@connect((state)=>{
  //需要哪些状态数据
  return {num : state.manageCompany}
} ,{ hire, hireAsync ,fire })


到此,登录已经实现了。
Dashboard.js也要实现一个登出的功能:
//引入`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>
        {/* 指定路由跳转的导航 */}
        <ul>
          <li>
            <Link to={`${match.url}`}>总部</Link>
          </li>
          <li>
            <Link to={`${match.url}/tecDep`}>技术部</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
    )
  }
}

至此已经实现了页面登录登出的切换效果。



上代码:
App.js
import React , { Component } from 'react'
import { connect } from 'react-redux'
import { hire, hireAsync ,fire } from './index.redux'

//状态映射属性
@connect((state)=>{
  //需要哪些状态数据
  return {num : state.manageCompany}
} ,{ hire, hireAsync ,fire })
class App extends Component {
  render() {
    return (
      <div>
        <h1>公司现在有{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>当前尚未登录</h2>
        <p onClick={this.props.loginAction}>点击登录</p>
      </div>
    )
  }
}
export default Auth


Auth.redux.js
//管理登录验证相关的信息和事件
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'

//定义两个无状态组件
function tecDep() {
  return <h2>技术部</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>
        {/* 指定路由跳转的导航 */}
        <ul>
          <li>
            <Link to={`${match.url}`}>总部</Link>
          </li>
          <li>
            <Link to={`${match.url}/tecDep`}>技术部</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创建store,通过compose把几个函数组合起来
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'

// 导出并且定义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!

相关文章

网友评论

    本文标题:【React.js 14】react-router4配合Redu

    本文链接:https://www.haomeiwen.com/subject/exvthftx.html