8 路由
项目使用react-router的最近版本5.0,看npm时你会发现一句话
This package provides the core routing functionality for React Router, but you might not want to install it directly. If you are writing an application that will run in the browser, you should instead install react-router-dom
.
所以我在项目中直接下载的 react-router-dom
.
npm install --save react-router-dom
// App.js
import React from 'react';
import './App.scss';
// 多个路由切换需要用 Switch
import { BrowserRouter, Route, Redirect, Switch } from 'react-router-dom'
import Home from './pages/Home'
import User from './pages/User'
import About from './pages/About'
import NoMatch from './pages/NoMatch'
function App() {
return (
<BrowserRouter >
<Switch>
<Route exact path="/" component={Home}/>
<Route path="/about" component={About} />
<Route path="/user" component={User} />
<Redirect to="/" />
{/* <Route component={NoMatch} /> */}
</Switch>
</BrowserRouter>
);
}
export default App;
这里有2中路由模式
1)<BrowserRouter>
这种模式使URL与UI保持一致。http://localhost:3000/ 使用 HTML5 提供的 history API (pushState
, replaceState
和 popstate
事件) 来保持 UI 和 URL 的同步。
属性
basename: string
所有位置的基准 URL。如果你的应用程序部署在服务器的子目录,则需要将其设置为子目录。basename
的正确格式是前面有一个前导斜杠,但不能有尾部斜杠。
<BrowserRouter basename="/calendar">
<Link to="/today" />
</BrowserRouter>
forceRefresh: bool
如果为 true
,在导航的过程中整个页面将会刷新。一般情况下,只有在不支持 HTML5 history API 的浏览器中使用此功能。
const supportsHistory = 'pushState' in window.history;
<BrowserRouter forceRefresh={!supportsHistory} />
getUserConfirmation: func
用于确认导航的函数,默认使用 window.confirm。例如,当从 /a
导航至 /b
时,会使用默认的 confirm
函数弹出一个提示,用户点击确定后才进行导航,否则不做任何处理。译注:需要配合 <Prompt>
一起使用。
// 这是默认的确认函数
const getConfirmation = (message, callback) => {
const allowTransition = window.confirm(message);
callback(allowTransition);
}
<BrowserRouter getUserConfirmation={getConfirmation} />
keyLength: number
location.key
的长度,默认为 6
。
<BrowserRouter keyLength={12} />
http://www.home.com:8080//location/page.html?ver=1.0&id=timlq#love
window.location.search 查询(参数)部分。除了给动态语言赋值以外,我们同样可以给静态页面,并使用javascript来获得相信应的参数值 返回值:?ver=1.0&id=timlq
window.location.hash 锚点 返回值:#love
2)<HashRouter>
这种模式是hash后面的URL与UI保持一致。http://localhost:3000/#/
这种模式有一个缺陷,就是url中参数不是很好获取到,window.location.search 获取到的是url后面的?加参数,如果hash模式,会获取不到。这种模式稍微有点影响美观。
basename: string
所有位置的基准 URL。basename
的正确格式是前面有一个前导斜杠,但不能有尾部斜杠。
<HashRouter basename="/calendar">
<Link to="/today" />
</HashRouter>
上例中的 <Link>
最终将被呈现为:
<a href="#/calendar/today" />
getUserConfirmation: func
用于确认导航的函数,默认使用 window.confirm。
// 这是默认的确认函数
const getConfirmation = (message, callback) => {
const allowTransition = window.confirm(message);
callback(allowTransition);
}
<HashRouter getUserConfirmation={getConfirmation} />
hashType: string
window.location.hash
使用的 hash
类型,有如下几种:
slash
- 后面跟一个斜杠,例如 #/ 和 #/sunshine/lollipopsnoslash
- 后面没有斜杠,例如 # 和 #sunshine/lollipopshashbang
- Google 风格的 ajax crawlable,例如 #!/ 和 #!/sunshine/lollipops
默认为 slash
。
开发过程中,需要查阅的路由资料可以参考下面链接
https://www.jianshu.com/p/97e4af32811a
9 mobx