react-router 和 history
- react-router的依赖基础 - history;
- history是一个独立的第三方js库,可以用来兼容在不同浏览器、不同环境下对历史记录的管理,拥有统一的API。
history
具体来说里面的history分为三类:
- 老浏览器的history: 主要通过hash来实现,对应createHashHistory
- 高版本浏览器: 通过html5里面的history,对应createBrowserHistory
- node环境下: 主要存储在memeory里面,对应createMemoryHistory 三个API的大致的技术实现如下:
- createBrowserHistory: 利用HTML5里面的history
- createHashHistory: 通过hash来存储在不同状态下的history信息
- createMemoryHistory: 在内存中进行历史记录的存储
执行URL前进
- createBrowserHistory: pushState、replaceState
- createHashHistory: location.hash=*** location.replace()
- createMemoryHistory: 在内存中进行历史记录的存储
伪代码实现如下:
// createBrowserHistory(HTML5)中的前进实现
function finishTransition(location) {
...
const historyState = { key };
...
if (location.action === 'PUSH') ) {
window.history.pushState(historyState, null, path);
} else {
window.history.replaceState(historyState, null, path)
}
}
// createHashHistory的内部实现
function finishTransition(location) {
...
if (location.action === 'PUSH') ) {
window.location.hash = path;
} else {
window.location.replace(
window.location.pathname + window.location.search + '#' + path
);
}
}
基本使用
// src/index.jsx
// ...
import { Router, Route, Link } from 'react-router-dom';
import { createBrowserHistory } from 'history';
const appHistory = createBrowserHistory();
ReactDOM.render(
<Provider store={store}>
<Router history={appHistory}>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/login">Login</Link></li>
</ul>
<Route exact path="/" component={HomePage} />
<Route path="/login" component={LoginPage} />
</div>
</Router>
</Provider>,
document.getElementById('root'),
);
参考链接
zhenhua-lee.github.io/react/histo… zhenhua-lee.github.io/repository/…