深入react-router-dom(v5.2.1)[for WEB]的使用

588 阅读4分钟

深入react-router-dom(v5.2.1)[for WEB]的使用

基本组件解释

  • <BrowserRouter/>:使用HTML5原生api的路由
  • <HashRouter/>:使用hash模拟的路由
  • <Link/>:路由跳转链接(普通链接会导致强制刷新,使用Link可以附带参数)
  • <NavLInk>:增强版的标签,可定义激活/未激活状态
  • <Promopt/>:用于在离开页面之前提示用户。配合的getUserConfirmation使用可以改变window.confirm()默认动作
  • <Redirect/>:重定向路由
  • <Route/>:路由渲染出口
  • <Switch/>:开启懒惰匹配

嵌套路由原理

  • /home/aboutus为例
  • 首先在顶级匹配/home渲染home组件
  • home组件内部定义子路由继续进行匹配(路由的匹配是由外而内的)
  • 子路由必须是完整路径/home/aboutus(这是V5.2.1的限制,不能使用相对路径,V6更新之后支持相对路径)
  • 子路由继续匹配到/home/aboutus就会进行渲染

<BrowserRouter/> as <Router/>

  • 属性详解
    • basename:根路径
    • getUserConfirmation:配合<Prompt/>修改其默认行为
    • forceUpdate:强制全局刷新
    • keyLength:location.key的长度,默认为6
    • children:渲染的子元素

<HashRouter/> as <Router/>

  • 属性详解
    • basename
    • getUserConfirmation
    • hashType:模拟hash类型
    • children

<Link/>

  • 属性详解

    • to

      • to = {"/any"}
        
      • to = { (currentLocation) => newLocation }
        
      • to = {
        	pathname: "/course",
            search: "?name=ycp&age=21",
            hash: "#thehash",
            state: {dataToBeTransfer: 'hello'}
        }
        
    • replace

    • innerRef:用于访问组件的基础引用

      • innerRef = {
        	node => newNode
        }
        
      • let linkRef = React.createRef()
        innerRef = {
            
        }
        
    • component:待渲染组件

    • others:需要添加到内部<a/>标签上的属性

<NavLink/>

  • 属性详解

    • activeClassName:激活时候的类名,默认值是.active

    • activeStyle:激活时候的样式对象

    • exact:精确匹配,区别于默认的匹配模式(在匹配/home/other时顶级的/home也会命中并激活当前<Link/>),添加exact之后只会命中精确匹配的路由并激活,而非模糊匹配。所以在使用嵌套路由的时候,父级不应当开启exact模式

    • strict:是否考虑末尾的斜杠对匹配的影响

    • isActive:为该Link导向的路由地址是否匹配到路由出口添加额外的逻辑操作,可以更加细粒度的根据匹配到的路由来修改Link的是否为'Active'的状态。

      • isActive{(match, location) => {
        	if(!match){
        		return false //不匹配就不激活
        	}
            //other operation...
        }}
        
    • location:

      • {
          key: 'ac3df4', // not with HashHistory! //可以通过 key 的变化来刷新页面
          pathname: '/somewhere',
          search: '?some=search-string',
          hash: '#howdy',
          state: {
            [userDefined]: true
          }
        }
        

<Prompt/>

  • 属性详解
    • message:传递给window.confirm()的确认信息
    • when:可以通过传递的布尔值控制<Prompt/>而非只在离开路由时

<Redirect/>

  • 属性详解
    • to
      • string
      • object
    • push:以push的模式将原先的路由访问记录推入history,而非默认的replace
    • from:指定重定向的来源path,再通过to重定向出去
    • exact
    • strict
    • sensitive:是否区分大小写

<Route/>

  • route props

    • match

      • history:历史记录

      • location:存放路径、查询参数、hash、state传参

        • {
              pathname: "/home",
              search: "?name=ycp",
              hash: "#any",
              state: undefined //通过to传递的对象中的state
          }
          
      • match:当前路由、匹配到的路由、精确匹配与否、路由传参参数

        • {
              path: "/home/:id",
              url: "/home/1",
              isExact: true,
              params: {
              	id: 1
              }
          }
          
  • 路由渲染的三种方式

    • <Route path="/user/:username" component={User} /> //User can get route props √
      //最常规的形式
      
    • <Route path="/home" render={routeProps => <Component {...routeProps} />} />//Component can get route props √
      //可以方便地定义内联形式的组件而无需额外组件定义,通过回调传入route props(必须显式地传入)
      
    • <Route
            path={to}
            children={
              (routeProps) => (
                  <li className={routeProps.match ? "active" : ""}>
                          <Link to={to} {...rest} />			
                  </li>
              )
            }
      />
      //children定义的组件无论是否匹配都会被渲染,但是可以根据匹配情况进行按需渲染
      
  • 重要参数

    • path
      • string
      • string[]
      • RegExp
    • exact:当且仅当精确匹配时渲染
    • strict
    • location: object
      • 当您需要将 <Route/> 与当前历史位置以外的位置匹配时,这很有用(使用location.key
    • sensitive

<Switch/>

  • 重要参数

    • location:可以用来该<Switch/>下的所有路由的根路径

      • <Link to={"/about/address"}>Link to Address</Link>
        <Switch location={{pathname: "/about"}}>
        	<Route path="address" component={Address} />
        </Switch>
        
        {/* 这里的Route就是代表了"/about/address" */}
        
    • children:<Switch/> 的所有子元素都应该是 <Route/><Redirect/> 元素。只会呈现与当前位置匹配的第一个孩子。

      • 使用<Route/> | <Redirect/>注意点:没有path<Route/>和没有from<Redirect/>总是会被命中。

其他不常用组件

<MemoryRouter/> as </Router>

  • 解释
    • location只保存在内存中而不保存在浏览器记录栈中的Router

常用方法

generatePath:生成传参路由地址

  • import { generatePath } from "react-router";
    
    generatePath("/user/:id/:entity(posts|comments)", {
      id: 1,
      entity: "posts"
    });
    

编程式导航

  • 访问方式
    • this.props.history.push()
  • history自带方法
    • push(path: string | object, [state])
    • replcae(path: string | object, [state])
    • go(n: number)
    • goBack(n: number)
    • goForward(n: number)