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()方法。