React Router 速查笔记

前言

本文为 React Router 的一篇速查笔记,不定时会更新相关内容。

组件

路由组件

BrowserRouter

正常的 url 表现,但是需要配合 server 使用。

HashRouter

hash 路由,使用时会 URL 里会存在hash。

匹配组件

Route

匹配单个路由,可以嵌套组件。

Switch

可以嵌套多个 Route,只渲染被匹配到的其中一个 Route。

导航组件

Link 可以理解为一个链接,可以基于当前路由进行跳转。

NavLink 可以理解为一个特别的 Link,因为它可以通过设置 activeClassName 或者 activeStyle 来呈现点击时的样式。

Redirect

Redirect 可以直接跳转一个新的链接。

常见问题

一、如何获取 history 对象

通过 Route 组件获取

通过直接传递 props 获取

通过嵌套 withRouter 获取

  • 用法

    引入 withRouter 之后用它来包裹住目标组件。

    import React from 'react';
    import {withRouter} from 'react-router-dom';
    
    class Target extends React.Component {
        ...
        foo() {
            // 可以有效获取到 history
            console.log(this.props.history);
        }
    }
    
    export default withRouter(Target);
    
  • 原理

    官网中提到,withRouter 是一种高阶组件。以下是它的源码:

    我们注意到,withRouter 做了这样两件事情:

    • 利用 RouterContext.Consumer 二次封装 Component
    • context 注入到 Component 中作为它 props 的一部分

    因此很容发现,withRouter 其实是利用了 ProviderCunsumer 进行了状态传递,以此来获取 history 等路由属性。

未完待续……

原文地址:https://www.cnblogs.com/pigpigever/p/13855625.html