React-Router常見API


React-Router是React項目中處理路由的庫。

1. HashRouter

通過hashchange監聽路由的變化,通過window.location.hash賦值觸發監聽的變化。

本質是一個react中的context對象,向下傳參,傳遞參數有三種:

1. location

有四個屬性:state, pathname, search, hash

state: 可以用來在路由中傳遞參數

pathname:  指定路由

2. history

主要有兩個方法:

push: 可以實現跳轉路由

// 傳遞對象
this.props.history.push({pathname: url, state: xxx})
// 傳遞路由
this.props.history.push(url)

3.match

通過該字段可以知道當前組件的路由是否和地址欄中路由相同。

應用:

實現單擊后菜單呈現選中狀態
import React, { Component } from 'react'
import { Route, Link } from '../react-router-dom';

export default function ({to, exact, ...rest}) {
  // 實現單擊后鏈接呈現選中狀態
  return (
    <Route
      path={to}
      exact={exact}
      children={(props) => {
        return <Link to={to} className={props.match ? 'active' : ''}>{rest.children}</Link>
      }}
    />
  )
}

2.BrowserRouter

通過onpopstate事件監聽通過點擊前進后退/調用back()等方法的操作。通過改寫pushState方法,監聽頁面中路由的變化。

其他和HashChange基本相同

3. Route

用於渲染指定路由的組件。children屬性時,可以不指定路由。

用於匹配路由: path, exact

path: 指定路由

exact: 嚴格匹配

有三個屬性用於渲染組件:

1. component

當path值匹配時,渲染component中的組件

2.render

當path匹配時,可以自定義渲染邏輯。相當於React中的render props復用組件功能。

如:受保護路由的實現。

import React from 'react';
import Route from '../react-router-dom/Route';
import { Redirect } from '../react-router-dom';

export default function({component:Component, ...rest}) {
  return (
    <Route {...rest}
      render={(props) => localStorage.getItem('login') ? 
      <Component {...props} /> 
      : <Redirect to={{pathname: '/login', state: {from: props.location.pathname}}} />}
    />
  )
}

3.children

無論路由是否匹配,都會渲染。

如: 菜單的選中狀態

import React, { Component } from 'react'
import { Route, Link } from '../react-router-dom';

export default function ({to, exact, ...rest}) {
  // 實現單擊后鏈接呈現選中狀態
  return (
    <Route
      path={to}
      exact={exact}
      children={(props) => {
        return <Link to={to} className={props.match ? 'active' : ''}>{rest.children}</Link>
      }}
    />
  )
}

4. Link

to屬性有兩種參數形式

1. 對象類型

<Link to={{pathname: url, state: {xx:xx}}}/>

2. 字符串

<Link to="/user">

5. Switch/Redirect

Switch(只匹配一個路由)和Redirect(前面的都不匹配時走這個路由)配合使用。

重定向方式有兩種:

1)組件重定向: <Redirect />

2)方法重定向 this.props.history.push()

6. withRouter

對於非Route加載的組件,想要使用從Route中傳遞的history,location,match屬性,使用該方法。

其本質是個高階組件。

import React from 'react';
import Route from './Route';

export default function(WrappedComponent) {
  return (props) => <Route component={WrappedComponent} />
}

7. Prompt

1. 屬性

1. when

根據該屬性進行路由的攔截。當為true時,彈出一個下confirm框。

2.message

用於顯示攔截的信息, 本質是個函數。

2. 原理

基於history.push()和history.block()方法。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM