react-router-dom基础

路由的种类

  • 页面路由

    1
    2
    window.location.href = 'http://www.baidu.com';
    history.back();
  • hash 路由

    1
    2
    3
    4
    window.location = '#hash';
    window.onhashchange = function(){
    console.log('current hash:', window.location.hash);
    }
  • h5路由

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    // 推进一个状态
    history.pushState('name', 'title', '/path');
    // 替换一个状态
    history.replaceState('name', 'title', '/path');
    // popstate
    window.onpopstate = function(){
    console.log(window.location.href);
    console.log(window.location.pathname);
    console.log(window.location.hash);
    console.log(window.location.search);
    //……
    }

react-router学习推荐地址:

react-router

  • <BrowserRouter>,<HashRouter>,路由方式
  • <Route>,路由规则
  • <Switch>,路由选项
  • <Link>,<NavLink>,跳转导航
  • <Redirect>,自动跳转

react-router-dom基本使用

  • 例:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    import React from 'react';
    import ReactDOM from 'react-dom';
    import { BrowserRouter as Router, Switch, Route, Link } from 'react-router-dom'
    class A extends React.Component{
    constructor(props){
    super(props)
    }
    render(){
    return (
    <div>
    Component A
    <Switch>
    <Route exact path={`${this.props.match.path}`} render={(route) => {
    return <div>当前组件是不带参数的A</div>
    }}/>
    <Route path={`${this.props.match.path}/sub`} render={(route) => {
    return <div>当前组件是Sub</div>
    }}/>
    <Route path={`${this.props.match.path}/:id`} render={(route) => {
    return <div>当前组件是带参数的A, 参数是:{route.match.params.id}</div>
    }}/>
    </Switch>
    </div>
    )
    }
    }
    class B extends React.Component{
    constructor(props){
    super(props)
    }
    render(){
    return <div>Component B</div>
    }
    }
    class Wrapper extends React.Component{
    constructor(props){
    super(props)
    }
    render(){
    return (
    <div>
    <Link to="/a">组件A</Link>
    <br/>
    <Link to="/a/123">带参数的组件A</Link>
    <br/>
    <Link to="/b">组件B</Link>
    <br/>
    <Link to="/a/sub">/a/sub</Link>
    {this.props.children}
    </div>
    );
    }
    }
    ReactDOM.render(
    <Router>
    <Wrapper>
    <Route path="/a" component={A}/>
    <Route path="/b" component={B}/>
    </Wrapper>
    </Router>,
    document.getElementById('app')
    );