react-router官方文档-WEB篇连接html
使用了HTML5的history API, (pushState, replaceState和popState等方法)来保证视图与URL的同步。node
全部位置的基本URL。若是您的应用程序是从服务器上的子目录提供的,则须要将其设置为子目录。正确格式化的基本名称应该有一个主要的斜杠,但没有尾部斜杠。react
eg:git
<BrowserRouter basename="/calendar"/> <Link to="/today"/> // renders <a href="/calendar/today">
默认使用
window.confirm
方法github
eg:web
// this is the default behavior const getConfirmation = (message, callback) => { const allowTransition = window.confirm(message) callback(allowTransition) } <BrowserRouter getUserConfirmation={getConfirmation}/>
强制刷新浏览器,在不支持HTML5 history API的浏览器中使用npm
eg:api
const supportsHistory = 'pushState' in window.history <BrowserRouter forceRefresh={!supportsHistory}/>
location.key
的长度,默认值为6数组
A single child element to render.浏览器
不支持
location.key
与location.state
建议使用
BrowserRouter
为你的应用提供声明性可访问的导航
指向的路径
指向的location
为true时,新的路径或者location会替换当前的路径而不是在历史记录中建立一条新的。
一个特殊的Link组件,它能够为其所属组件添加class或者style样式等属性。
当该路由成功匹配时, 添加class到该路由对应的即将渲染的组件,默认值为active。
eg:
<NavLink to="/faq" activeClassName="selected" >FAQs</NavLink>
组件被渲染时,为其添加样式
eg:
<NavLink to="/faq" activeStyle={{ fontWeight: 'bold', color: 'red' }} >FAQs</NavLink>
同Route的exact属性
同Route的strict属性
为匹配一个路由除了路径匹配之外,添加更多的判断条件,返回值为
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>
默认值是当前history的location,传入其余location能够替代
isActive
函数中的location对象
在非浏览器环境,模仿浏览器history对象所作的那样记录url的变化。例如React Native。
渲染Redirect组件会重定向到一个新的location而且覆盖当前的location的历史记录。
重定向的路径
重定向目标的location对象
为true时,不会覆盖当前的location的历史记录,而是建立一条新的记录。
重定向以前的路径
仅当Redirect组件在Switch组件中渲染时可使用。
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渲染组件的方法有三种, 须要注意的是每一个Route组件只能使用其中一种渲染方法。
<Route component>
<Route render>
<Route children>
以上的每一个渲染方法都传入了三个包含路由信息的参数。
match
location
history
当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);
不一样于
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}/>
传入的参数与
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> )}/>
当Route组件不填写
path
属性时,默认匹配并渲染对应组件。
Any valid URL path that path-to-regexp understands.
为true表示只有当
path
准确匹配location.path
,才会渲染组件。
path | location.path | exact | matches? |
---|---|---|---|
/one | /one/two | true | no |
/one | /one/two | false | yes |
当为true时,具备尾部斜杠的路径将仅与具备尾部斜杠的location.pathname匹配。当location.pathname中有其余URL段时,这不起做用。
strict为true时
path | location.path | matches? |
---|---|---|
/one/ | /one | no |
/one/ | /one/ | yes |
/one/ | /one/two | yes |
与exact搭配使用,两个都为true时
path | location.path | matches? |
---|---|---|
/one/ | /one | no |
/one/ | /one/ | yes |
/one/ | /one/two | no |
一般一个Route组件的
path
会与当前的路由进行匹配,然而Route还有支持传入包含其余路由信息的location对象以便执行某些操做。
eg: animated-transitions的示例中,在Route
组件中传入了location对象用于执行离开动画。
做为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') );
适用于服务端渲染
内部仅渲染一个与当前路由匹配的视图。
举个例子当前匹配路径为/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会中止匹配,并渲染已匹配到的路由对应的组件。
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)
安装
npm install --save react-router-config