react-router-v4
app.js
1 | import React, { Component } from 'react'; |
Navigation.js
1 | import React from 'react' |
基本组件 3种
- router components
- route matching components
- navigation components
1 | import { BrowserRouter, Route, Link } from "react-router-dom"; |
router components 2种
有2种<BrowserRouter>
和 <HashRouter>
routers. 都会创建一个history
对象
通常 <BrowserRouter>
用在 a server that responds to requests and a <HashRouter>
用在static file server.
Route Matching 2种
<Route>
and <Switch>
.
<Route>
就是比较 when location = { pathname: '/about' }
和 <Route path='/about' component={About}/>
中的path='/about'
, 每个<Route />
都会比较, 最小匹配, 匹配上的render
, 没匹配上的render null
, 没有写path
的会始终匹配.
<Switch>
只会递归的匹配第一个非exact
匹配上的(注意嵌套模式), 而没写path
的<Route />
当做兜底的情况.
exact
是用来完全匹配的path
1 | import { Route, Switch } from "react-router-dom"; |
Route Rendering Props
<Route>
有3个props
: component
, render
, and children
.
1 | const Home = () => <div>Home</div>; |
Navigation
用<Link>
, 然后会render成<a>
<NavLink>
是一种特殊的 <Link>
当match
上location的
的时候会加上activeClassName
就是class
强制navigation的话用<Redirect>
1 | <Link to="/">Home</Link> |
服务端的
参考
React Router tutorial for beginners | React Router v4 2018
React Router v4 Tutorial+quick Start