React-6-路由

一、介绍及安装使用react-router

1.特点

①路由也是组件

②分布式配置,在各个组件都可以使用

③包含式配置,可匹配多个路由

2.安装使用

npm install react-router-dom --save

使用步骤:

  • 引入顶层路由BrowserRouter组件包裹根组件
  • 引入Link组件编写路由导航
  • 引入Route组件编写导航配置
  • 编写导航配置对应的component组件
import React, { Component } from 'react'
import { BrowserRouter, Link, Route, Switch } from 'react-router-dom'


function Home() {
    return <div>首页</div>
}

function Course() {
    return <div>课程</div>
}

function Mine() {
    return <div>我的</div>
}

function NotFound() {
    return <div>没有的组件</div>
}

function App() {
    return (
        <div>
            <ul>
                <li><Link to="/">首页</Link></li>
                <li><Link to="/course">课程</Link></li>
                <li><Link to="/mine">我的</Link></li>
                <li><Link to="/notfound">没有的组件</Link></li>
            </ul>  
            <Switch>
                <Route path="/" exact component={Home}></Route>
                <Route path="/course" exact component={Course}></Route>
                <Route path="/mine" exact component={Mine}></Route>
                <Route component={NotFound}></Route>                
            </Switch>          
        </div>

    )
}

export default class RouterSample extends Component {
    render() {
        return (
            <div>
                <h1>学习react-router</h1>
                <BrowserRouter>
                  <App></App>
                </BrowserRouter>
            </div>
        )
    }
}
RouterSample.js

注:Switch会从上至下最多只匹配一个路由组件

 

二、react-router的路由传参取参

function Detail({match, location, history}) {
    return (
        <div>
            我是{match.params.course}详情页
            <button onClick={()=>history.push({pathname: '/', state: {foo: 'bar'}})}>返回首页</button>
        </div>
    )
}

function Home({location}) {
    console.log(location)
    return (
        <div>
            <p>首页</p>
            {location.state ? <div>从详情页带来的foo: {location.state.foo}</div> : <div></div>}
        </div>
    )
}

 

三、路由守卫

react路由守卫也是一个组件,最后返回的还是Route组件

<RouteGuard path="/mine" component={Mine}></RouteGuard>
class RouteGuard extends Component {
    state = {
        isLogin: false
    }
    render() {
        const {component:Component, ...otherProps} = this.props
        return (
            <Route {...otherProps} render={props=>(
                this.state.isLogin ? <Component {...props}></Component> : <Redirect to={{pathname: '/login', state: {from: props.location.pathname}}}></Redirect>
            )}>
            </Route>
        )
    }
}

 

posted @ 2020-02-01 17:08  不可思议的猪  阅读(965)  评论(0编辑  收藏  举报