react-router 中的history
eact-router 是建立在history之上的
history 一个管理js应用session会话历史的js库。它将不同环境(浏览器,node...)的变量统一成了一个简易的API来管理历史堆栈、导航、确认跳转、以及sessions间的持续状态。
//基本 使用
import { createHistory } from 'history'
const history = createHistory()
// 当前的地址
const location = history.getCurrentLocation()
// 监听当前的地址变换
const unlisten = history.listen(location => {
console.log(location.pathname)
})
// 将新入口放入历史堆栈
history.push({
pathname: '/the/path',
search: '?a=query',
// 一些不存在url参数上面的当前url的状态值
state: { the: 'state' }
})
// When you're finished, stop the listener
unlisten()
你也可以使用 history对象来的方法来改变当前的location:
- push(location)
- replace(location)
- go(n)
- goBack()
- goForward()
一个 history 知道如何去监听浏览器地址栏的变化, 并解析这个 URL 转化为 location 对象, 然后 router 使用它匹配到路由,最后正确地渲染对应的组件。
location对象包括:
pathname 同window.location.pathname
search 同window.location.search
state 一个捆绑在这个地址上的object对象
action PUSH, REPLACE, 或者 POP中的一个
key 唯一ID
常用的三种history
// HTML5 history, 推荐
import createHistory from 'history/lib/createBrowserHistory'
// Hash history
import createHistory from 'history/lib/createHashHistory'
// 内存 history (如:node环境)
import createHistory from 'history/lib/createMemoryHistory'
createHashHistory
这是一个你会获取到的默认 history ,如果你不指定某个 history (即 <Router>{/* your routes */}</Router>)。它用到的是 URL 中的 hash(#)部分去创建形如 http://example.com/#/some/path 的路由。
Hash history 是默认的,因为它可以在服务器中不作任何配置就可以运行,并且它在全部常用的浏览器包括 IE8+ 都可以用。但是我们不推荐在实际生产中用到它,因为每一个 web 应用都应该有目的地去使用createBrowserHistory。
createBrowserHistory
Browser history 是由 React Router 创建浏览器应用推荐的 history。它使用 History API 在浏览器中被创建用于处理 URL,新建一个像这样真实的`URL example.com/some/path`
createMemoryHistory
Memory history 不会在地址栏被操作或读取。这就解释了我们是如何实现服务器渲染的。同时它也非常适合测试和其他的渲染环境(像 React Native )。