React-router4官方文档学习笔记-WEB篇

react-router官方文档-WEB篇链接

BrowserRouter

使用了HTML5的history API, (pushState, replaceState和popState等方法)来保证视图与URL的同步。

basename: string

所有位置的基本URL。如果您的应用程序是从服务器上的子目录提供的,则需要将其设置为子目录。正确格式化的基本名称应该有一个主要的斜杠,但没有尾部斜杠。

eg:

<BrowserRouter basename="/calendar"/>
<Link to="/today"/> // renders <a href="/calendar/today">

getUserConfirmation: func

默认使用window.confirm方法

eg:

// this is the default behavior
const getConfirmation = (message, callback) => {
  const allowTransition = window.confirm(message)
  callback(allowTransition)
}

<BrowserRouter getUserConfirmation={getConfirmation}/>

forceRefresh: bool

强制刷新浏览器,在不支持HTML5 history API的浏览器中使用

eg:

const supportsHistory = 'pushState' in window.history
<BrowserRouter forceRefresh={!supportsHistory}/>

keylength: number

location.key的长度,默认值为6

children: node

A single child element to render.

HashRouter

不支持location.keylocation.state

建议使用BrowserRouter

Link

为你的应用提供声明性可访问的导航

to: string

指向的路径

to: object

指向的location

replace: bool

为true时,新的路径或者location会替换当前的路径而不是在历史记录中创建一条新的。

NavLink

一个特殊的Link组件,它可以为其所属组件添加class或者style样式等属性。

activeClassName: string

当该路由成功匹配时, 添加class到该路由对应的即将渲染的组件,默认值为active。

eg:

<NavLink
  to="/faq"
  activeClassName="selected"
>FAQs</NavLink>

activeStyle

组件被渲染时,为其添加样式

eg:

<NavLink
  to="/faq"
  activeStyle={{
    fontWeight: 'bold',
    color: 'red'
   }}
>FAQs</NavLink>

exact: bool

同Route的exact属性

strict: bool

同Route的strict属性

isActive: func

为匹配一个路由除了路径匹配以外,添加更多的判断条件,返回值为bool类型

eg:

// only consider an event active if its event id is an odd number
const oddEvent = (match, location) => {
  if (!match) {
    return false
  }
  const eventID = parseInt(match.params.eventID)
  return !isNaN(eventID) && eventID % 2 === 1
}

<NavLink
  to="/events/123"
  isActive={oddEvent}
>Event 123</NavLink>

location: object

默认值是当前history的location,传入其他location可以替代isActive函数中的location对象

MemoryRouter

在非浏览器环境,模仿浏览器history对象所做的那样记录url的变化。例如React Native。

Redirect

渲染Redirect组件会重定向到一个新的location并且覆盖当前的location的历史记录。

to: string

重定向的路径

to: object

重定向目标的location对象

push: bool

为true时,不会覆盖当前的location的历史记录,而是创建一条新的记录。

from: string

重定向之前的路径

仅当Redirect组件在Switch组件中渲染时可以使用。

Route

React-router最基础也最重要的组件, 它规定了当匹配到指定路由时渲染哪些组件。

eg:

 import { BrowserRouter as Router, Route } from 'react-router-dom';

<Router>
  <div>
    <Route exact path="/" component={Home}/>
    <Route path="/news" component={NewsFeed}/>
  </div>
</Router>
<div>
  <Home/>
  <!-- react-empty: 2 -->
</div>
<div>
  <!-- react-empty: 1 -->
  <NewsFeed/>
</div>

Route render methods--Route渲染指定组件的方法

Route渲染组件的方法有三种, 需要注意的是每个Route组件只能使用其中一种渲染方法

  • <Route component>
  • <Route render>
  • <Route children>

Route props -- Route的render方法默认包含的参数

以上的每个渲染方法都传入了三个包含路由信息的参数。

  • match
  • location
  • history

component

当location与路由匹配时, 是用于渲染组件的方法之一,此时react-router会调用React.createElement方法为给定的组件创建一个新的React节点。

注意:如果使用内联函数的形式赋值给component属性,意味着每次render你都会得到一个全新的组件,触发组件unmounting方法和组件的mounting状态。

常用写法: 函数组件与类组件

eg1: Function Component 直接在props中获取路由信息

<Route path="/user/:username" component={User}/>

const User = ({ match }) => {
  return <h1>Hello {match.params.username}!</h1>
}

eg2: Class Component使用withRouter方法可以在组件中注入match, location,history对象,然后通过this.props获取。

//App.js
import User from './User.js';
import React from 'react';
import {
  BrowserRouter as Router
} from 'react-router';
import ReactDOM from 'react-dom';

class App extends React.Component {
  render() {
    return (
      <div>
        <Route path="/user/:username" component={User}/>
      </div>
    )
  }
}

ReactDOM.render(
  <Router>
    <App />
  </Router>, document.getElementById('root')
);

//User.js
import { withRouter } from 'react-router';
import React from 'react';
class User extends React.Component {
  render() {
    return (
      <h1>
        Hello {this.props.match.params.username}!
      </h1>
    );
  }
}

export default withRouter(User);

render: func

不同于component属性, 每次render时,会更新已存在的组件而不是创建一个新的组件。

eg:

// convenient inline rendering
<Route path="/home" render={() => <div>Home</div>}/>

// wrapping/composing
const FadingRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={props => (
    <FadeIn>
      <Component {...props}/>
    </FadeIn>
  )}/>
)

<FadingRoute path="/cool" component={Something}/>

children: func

传入的参数与render相同, 但是其中match对象在未路由匹配时值为null。可以灵活使用这一点。

eg1:

<ul>
  <ListItemLink to="/somewhere"/>
  <ListItemLink to="/somewhere-else"/>
</ul>

const ListItemLink = ({ to, ...rest }) => (
  <Route path={to} children={({ match }) => (
    <li className={match ? 'active' : ''}>
      <Link to={to} {...rest}/>
    </li>
  )}/>
)

eg2:

 <Route children={({ match, ...rest }) => (
  {/* Animate will always render, so you can use lifecycles
      to animate its child in and out */}
  <Animate>
    {match && <Something {...rest}/>}
  </Animate>
)}/>

path: string

当Route组件不填写path属性时,默认匹配并渲染对应组件。

Any valid URL path that path-to-regexp understands.

exact: bool

为true表示只有当path准确匹配location.path,才会渲染组件。

pathlocation.pathexactmatches?
/one/one/twotrueno
/one/one/twofalseyes

strict: bool

当为true时,具有尾部斜杠的路径将仅与具有尾部斜杠的location.pathname匹配。当location.pathname中有其他URL段时,这不起作用。

strict为true时

pathlocation.pathmatches?
/one//oneno
/one//one/yes
/one//one/twoyes

与exact搭配使用,两个都为true时

pathlocation.pathmatches?
/one//oneno
/one//one/yes
/one//one/twono

location

通常一个Route组件的path会与当前的路由进行匹配,然而Route还有支持传入包含其他路由信息的location对象以便执行某些操作。

eg: animated-transitions的示例中,在Route组件中传入了location对象用于执行离开动画。

Router

作为app最底层的路由组件

主要有以下五种使用场景

  • <BrowserRouter>
  • <HashRouter>
  • <MemoryRouter>
  • <NativeRouter>
  • <StaticRouter>

eg:

import { Router } from 'react-router'
import createBrowserHistory from 'history/createBrowserHistory'

const history = createBrowserHistory()

<Router history={history}>
  <App/>
</Router>

如果引用的是react-router-dom,则使用如下的引用方式, 效果和上方的代码相同。

import {
  BrowserRouter as Router,
} from 'react-router-dom';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <Router>
    <App />
  </Router>, document.getElementById('root')
);

StaticRouter

适用于服务端渲染

Switch

内部仅渲染一个与当前路由匹配的视图。

举个例子当前匹配路径为/about时,比较不使用Switch与使用Switch的不同

eg: 不用Switch的情况

<Route path="/about" component={About}/>
<Route path="/:user" component={User}/>
<Route component={NoMatch}/>

//结果:About,User,NoMatch组件都渲染到视图中。

eg: 使用Switch的情况

import { Switch, Route } from 'react-router'

<Switch>
  <Route exact path="/" component={Home}/>
  <Route path="/about" component={About}/>
  <Route path="/:user" component={User}/>
  <Route component={NoMatch}/>
</Switch>

//结果:仅渲染了About组件

原因: Switch内部顺序匹配当前路由,当匹配到/about时,Switch会停止匹配,并渲染已匹配到的路由对应的组件。

应用场景

Scroll to top

class ScrollToTop extends Component {
  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      window.scrollTo(0, 0)
    }
  }

  render() {
    return this.props.children
  }
}

export default withRouter(ScrollToTop)

React Router Config

github地址

安装

npm install --save react-router-config