react 路由

什么是路由

  • 路由是根据不同的 url 地址展示不同的内容或者页面。
  • 在 react 中,react-router-dom 包,可以友好的帮我们解决 react components 到 url 之间的同步映射关系。

使用路由

  1. 安装路由

    $ npm install react-router-dom -S
    
  2. 引入路由

    import React, { Component } from 'react'
    // 引入路由文件
    import {
      HashRouter, // 哈希模式
      BrowserRouter, // history 模式
      Route,
      Link,
      Redirect, // 重定向
      Switch
    } from 'react-router-dom'
    
  3. 定义路由以及路由重定向

    • react 中路由,默认会进行模糊匹配,且不会自动停止
    • 加上 Switch 进行模糊匹配,匹配到第一个就停止匹配,也可以加上 exact,实现精准匹配
    export default class Router extends Component {
      render() {
        return (
          <HashRouter>
            <Switch>
              <Route path="/home" component={Home}/>
              <Router path="/login" component={Login}/>
              <Redirect from="/" to="/home" exact/>
              <Route path="*" component={NotFound}/>
            </Switch>
          </HashRouter>
        )
      }
    }
    
  4. 嵌套路由

    • 在对应的子组件中,引入路由,配置路由即可
    export default class Home extends Component {
      render() {
        return (
          <div>子组件中配置子路由</div>
            
          <Switch>
            <Route path="/list" component={List}/>
            <Redirect from="/" to="/list"/>
          </Switch>
        )
      }
    }
    
  5. 路由拦截

    • 使用三目运算对路由进行拦截
    export default class Router extends Component {
      render() {
        return (
          <HashRouter>
            <Switch>
              <Route path="/login" compoent={Login}/>
              <Route path="/" render={()=>{
                 localStorage.getItem('isLogin') ?
                 <DashBoard /> :
                 <Redirect to="/login"/>
              }}/>
            </Switch>
          </HashRouter>
        )
      }
    }
    
  6. 声明式导航

    • 利用 NavLink 标签 to 属性实现路由的跳转
    • activeClassName 可以给激活状态元素加上对应类名
    export default class NavBar extends Component {
      render() {
        return (
          <ul>
             <li>
               <NavLink to="/home" activeClassName="active">主页</NavLink>
             </li>
             <li>
               <NavLink to="/list" activeClassName="active">列表页</NavLink>
             </li>
             <li>
               <NavLink to="/center" activeClassName="active">个人中心</NavLink> 
             </li>
          </ul>
        )
      }
    }
    
  7. 编程式导航

    • this.props.history.push()
    clickHandle = (id) => {
        this.props.history.push(`/detail/${id}`)
    }
    
    // detail 页面接收动态参数: this.props.match.params.id
    
  8. 路由传参

    // 方式一: 利用 this.props.location.query 接收
    this.props.history.push({
        pathname: '/user',
        query: {
            a: 1,
            b: 2
        }
    })
    
    // 方式二:利用 this.props.location.state 接收
    this.props.history.push({
        pathname: '/user',
        state: {
            a: 1,
            b: 2
        }
    })
    
  9. withRouter 高阶组件

    • 普通组件如果没有使用路由的话, this.props 上是没有 history、location、match 等属性的
    • 如果我们在普通组件中需要用到这些属性,则可以借用 withRouter 来实现
    import React, { Component } from 'react'
    // 引入高阶组件
    import { withRouter } from 'react-router'
    
    class TopBar extends Component {
      render() {
        return (
          <div>
            <button onClick={this.exit}>退出登录</button>
          </div>
        )
      }
    
      exit = () => {
        //清除本地存储
        localStorage.removeItem('token')
    
        // 跳转到登录页
        this.props.history.push('/login')
      }
    }
    
    // 使用高阶组件,为 TopBar 传递 history、location、match 等属性
    export default withRouter(TopBar)
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值