React Router 4.0 (以下简称 RR4) 已经正式发布,它遵循React的设计理念,即万物皆组件。所以 RR4 只是一堆 提供了导航功能的组件(还有若干对象和方法),具有声明式(声明式编程简单来讲就是你只需要关心做什么,而无需关心如何去做,好比你写 React 组件,只需要 render 出你想要的组件,至于组件是如何实现的是 React 要处理的事情。),可组合性的特点。
- react-router React Router 核心
- react-router-dom 用于 DOM 绑定的 React Router
- react-router-native 用于 React Native 的 React Router
- react-router-redux React Router 和 Redux 的集成
- react-router-config 静态路由配置的小助手
引入 react-router-dom
import { BrowserRouter, Link, Route, Redirect, Switch } from 'react-router-dom'
简单例子
1 | import React from 'react' |
A
basename: string
The base URL for all locations. If your app is served from a sub-directory on your server, you’ll want to set this to the sub-directory. A properly formatted basename should have a leading slash, but no trailing slash.
getUserConfirmation: func
A function to use to confirm navigation. Defaults to using window.confirm.
forceRefresh: bool
If true the router will use full page refreshes on page navigation. You probably only want this in browsers that don’t support the HTML5 history API.
keyLength: number
The length of location.key. Defaults to 6.
###children: node
A single child element to render.
Provides declarative, accessible navigation around your application.
to: string
The pathname or location to link to.
to: object
The location to link to.
replace: bool
When true, clicking the link will replace the current entry in the history stack instead of adding a new one.
The Route component is perhaps the most important component in React Router to understand and learn to use well. Its most basic responsibility is to render some UI when a location matches the route’s path.
Consider the following code:
Rendering a
to: string
The URL to redirect to.
to: object
A location to redirect to.
push: bool
When true, redirecting will push a new entry onto the history instead of replacing the current one.
from: string
A pathname to redirect from. This can only be used to match a location when rendering a