react-router-dom中如何进行路由权限控制,路由验权,props传值

龚志文
2023-12-01

1.router.config.js 这里存放了所有路由

import React from 'react'
// import { Router, Route, IndexRoute, hashHistory, childRoutes/* , Redirect */ } from 'react-router'
import {BrowserRouter as Router, Route, Switch, hashHistory} from 'react-router-dom';
import App from '../App';
import About from '../pages/About'
import Login from '../pages/login/Login'
import Undefined from '../pages/404/404'
import List2 from '../pages/routerlist/list2';
import List3 from '../pages/routerlist/list3';
import Layout from '../pages/layout/layout'
import First from '../pages/layout/first'
import Second from '../pages/layout/secong'
const Routes = [
  { path: "/app", name: "app", component: App, auth: true },
  { path: "/layout", name: "Home", component: Layout,auth: true,
    routes: [
      {
        path: "/layout/first", 
        name: "first", 
        component: First,
        auth: true
      },
      {
        path: "/layout/second", 
        name: "second", 
        component: Second,
        auth: true
      }
    
    ]
 },
  { 
    path: "/list/list3", 
    name: "Home", 
    component: List3,
    auth: true
  },
  { path: "/", name: "/", component: Login, },
  { path: "*", name: "indexedDB", component: Undefined }
]
export default Routes;

2.route-with-sub-routes.js 路由控制展示函数

import React from 'react';
import {Route} from "react-router-dom";

const RouteWithSubRoutes = route => (
    <Route
        path={route.path}
        render={props => (
            // pass the sub-routes down to keep nesting
            <route.component {...props} routes={route.routes} />
        )}
    />
);
export default RouteWithSubRoutes;

3.index.js 这里是底层依赖启动加载项

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import * as serviceWorker from './serviceWorker';
import routes from './configs/router.config'
import RouteWithSubRoutes from './configs/route-with-sub-routes'
import 'antd-mobile/dist/antd-mobile.css';  // or 'antd-mobile/dist/antd-mobile.less'
import { Provider } from 'react-redux';
import configureStore from './redux/index.js';
import {BrowserRouter as Router,Route, Switch,Redirect } from 'react-router-dom';
import {
    update,
    add,
    rm
  } from './redux/actions'
  
// import { Button } from 'antd-mobile';
// ReactDOM.render(<Button>Start</Button>, mountNode);
const store = configureStore();
// console.log(store.getState(),'123');
// store.dispatch(update('libai'))
console.log(store.getState(),'123')
ReactDOM.render( 
    // let token = 'qwe'
    <Provider store={store} >
        {/* <Routes /> */}
        <Router>
        <Switch>
                         {routes.map((route, i) => <RouteWithSubRoutes key={i} {...route} />)}
                    </Switch>
        {/* <Switch>           
        { 
            routes.map((route, index) => { 
            // return <Route key={index} path={route.path} exact render={props =>
            //     (!route.auth ? (<route.component {...props} routes={route.routes}/>) : (true ? <route.component {...props} routes={route.routes} /> : 
            //     <Redirect to={{pathname: '/',state: { from: props.location }}} />)
            //     )} />
            return <Route key={index} path={route.path} exact render={props =>
                <route.component {...props} routes={route.routes}/>} />
        })

        }
        </Switch> */}
        </Router>
    </Provider>
    , 
    document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: http://bit.ly/CRA-PWA
serviceWorker.unregister();

4.layout.js 父路由

import './layout.css'
import React, { Component } from 'react';
import {BrowserRouter as Router, NavLink, Switch,Redirect,Route, Link} from 'react-router-dom';
// import { createForm } from 'rc-form';
import First from './first';
import Second from './secong';
import Dlist from './dlist';
import RouteWithSubRoutes from '../../configs/route-with-sub-routes'
class Layout extends React.Component {
    handleList (){
        console.log('方法传递');
    }
  render() {
    // const { getFieldProps } = this.props.form;
   
    return (
       <div>
           <div>
               layout
           </div>
           <Dlist title="组件传值" func={this.handleList}>
                <div>组件插入</div>
           </Dlist>
           <ul>
            {this.props.routes.map((route, i) => {
                return (
                    <li key={i}>
                        <NavLink to={route.path}>{route.name}</NavLink>
                    </li>
                )
            })}
            </ul>
           <div>
                {/* <Switch>
                    <Route path="/layout/first" component={First}/>
                    <Route path="/layout/second" component={Second}/>
                    {this.props.routes.map((route, index) => {
                         return <Route key={index} path={route.path} exact render={props =>
                                <route.component {...props} routes={route.routes}/>
                            } />
                    })}
                </Switch> */}
                  <Switch>
                            {this.props.routes.map((route, i) => <RouteWithSubRoutes key={i} {...route} />)}
                        </Switch>
            </div>
        </div>
        
    );
  }
}

// const BasicInputExampleWrapper = createForm()(BasicInputExample);
// ReactDOM.render(<BasicInputExampleWrapper />, mountNode);
// class Login extends Component {
//   render() {
//     return (
//       <BasicInputExample />
//     );
//   }
// }

export default Layout;

5.first.js 子路由


import React, { Component } from 'react';
import { HashRouter, Switch, Route, Redirect,withRouter } from 'react-router-dom';
class First extends React.Component {
    // constructor(props) {
    //     super(props)
    // }
  render() {
    // const { getFieldProps } = this.props.form;
    return (
       <div>
           first
        </div>
        
    );
  }
  componentDidMount(){
    setTimeout(()=>{
    this.props.history.push('/layout/second');
    },2000)
}
}

// const BasicInputExampleWrapper = createForm()(BasicInputExample);
// ReactDOM.render(<BasicInputExampleWrapper />, mountNode);
// class Login extends Component {
//   render() {
//     return (
//       <BasicInputExample />
//     );
//   }
// }

export default First;

6.secong.js 子路由


import React, { Component } from 'react';
import { HashRouter, Switch, Route, Redirect,withRouter } from 'react-router-dom';
class Second extends React.Component {
    // constructor(props) {
    //     super(props)
    //     }
  render() {
    // const { getFieldProps } = this.props.form;
    return (
       <div>
           second
        </div>
        
    );
  }
  componentDidMount(){
    setTimeout(()=>{
    this.props.history.push('/layout/first');
    },2000)
}
}

// const BasicInputExampleWrapper = createForm()(BasicInputExample);
// ReactDOM.render(<BasicInputExampleWrapper />, mountNode);
// class Login extends Component {
//   render() {
//     return (
//       <BasicInputExample />
//     );
//   }
// }

export default Second;

7.delist.js 子模块,进行props传值


import React, { Component } from 'react';
import { HashRouter, Switch, Route, Redirect,withRouter } from 'react-router-dom';
import {update} from '../../redux/actions'
import { connect } from 'react-redux'
class Dlist extends React.Component {
    constructor(props) {
        super(props)
        this.state = {isToggleOn: true,dmt:'12'};
        // this.handleClick2 = this.handleClick2.bind(this); 
    }
    handClick=()=>{
        console.log('btn is click');
        this.setState({
            dmt: '13'
          });
        console.log(this.refs.myNum.value);
    }
    // 必须使用箭头函数才能取到this
    handClick2=()=>{
        console.log('接收传递的消息');
        this.props.func();
        console.log(this);
    }
   
render() {
    // const { getFieldProps } = this.props.form;
    const { PayIncrease } = this.props
    return (
       <div>
          <div> delist</div>
          <div> {this.props.list}</div>
          <div> {this.props.title}</div>
          <div> {this.props.userName}</div>
          
          <input type="text" ref="myNum" />
          <div> {React.Children.map(this.props.children,function(child){
              return child

          })}</div>
          <button onClick={this.handClick}>clik me</button>
          <button onClick={this.props.func}>注册</button>
          <button onClick={this.handClick2}>方法传递</button>
          <button onClick={PayIncrease}>升职加薪</button>
        </div>
        
    );
  }
  componentDidMount(){
      console.log(this)
    //   console.log(store);
    this.props.func();
    // setTimeout(()=>{
    // this.props.history.push('/layout/second');
    // },2000)
}
}

// const BasicInputExampleWrapper = createForm()(BasicInputExample);
// ReactDOM.render(<BasicInputExampleWrapper />, mountNode);
// class Login extends Component {
//   render() {
//     return (
//       <BasicInputExample />
//     );
//   }
// }
//需要渲染什么数据
const getList = state => {
    console.log(state,'state')
    return {
        list: state.userInfo.cityName,
        userName:state.userInfo.userName
    }
}
console.log(getList, 'getList')
//需要触发什么行为,必须要引用redux中actions的方法
function mapDispatchToProps(dispatch) {
    // console.log(dispatch(update()),'dispatch')
    return {
        PayIncrease: () => {dispatch(update('libai'));console.log()},
        PayDecrease: () => dispatch()
    }
  }
// Dlist = connect()(Dlist)
export default connect(getList,mapDispatchToProps)(Dlist);

 

 类似资料: