react history 历史页面管理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/kangkang_style/article/details/88825977

history是为React Router提供核心功能的包。
它能轻松地在客户端为项目添加基于location的导航。

1. 安装
	npm install --save history
2. 类型
	import { createBrowserHistory, createHashHistory, createMemoryHistory } from 'history'
	存在三类history,分别时browser,hash,与 memory。history包提供每种history的创建方法。
	如果使用React Router,他会为你自动创建history对象,所以并不需要与history进行直接的交互。
3. 方法与属性
	location:属性  反映了当前应用所在的"位置"。
			    其包含了pathname,search,hash这种由'URL'派生出的属性。
			    每一个location都拥有一个与之关联且独一无二的key。
			    'key'用于特定location的识别,向特定location存储数据。
			    location可以拥有与之相关的状态。这是一些固定的数据,并且不存在于URL之中。
			    实例:
					{
						pathname: '/here',
						search: '?key=value',
						hash: '#extra-information',
						state: { modal: true },
						key: 'abc123'
					}
				当创建一个history对象后,需要初始化location。对于不同类型history这一过程也不相同。
	说明:
		我们只能访问当前location,history对象持续追踪着一组location。
		history也保存一个索引值,用来指向当前所对应的location。

	navigation:方法 navigation允许你改变当前location。
	
	push:方法 允许跳转到新的location。
			默认情况下,当你点击<Link>时,会调用history.push方法进行导航。
			当使用history.push()跳转到新的location时,被跳转location被清除。
			
	replace:方法 用法类似push,但被跳转location不会被清除。
	
	goBack: 方法 返回上一层页面
			实例:
				history.goBack()
				
	goForward: 方法 去往下一层页面
			实例:
				history.goForward()
				
	go: 方法 向前或向后跳转到指定页面
			实例:
				history.go(3)
				
4. 动态监听
	采用观察者模式,在location改变时,history会发出通知。
	每一个history对象都有listen方法,接受一个函数作为参数。
	React Router的router组件将会订阅history对象,这样当location变化时,其能重新渲染。	
	实例:
		history.listen(function (location) { ... })
				
5. 事物连接
		每一类history都拥有createHref方法,其使用location对象,输出URL。
		实例:
			const location = {
				pathname: '/one-fish',
				search: '?two=fish',
				hash: '#red-fish-blue-fish'
			}
			const url = history.createHref(location)
			const link = document.createElement('a')
			a.href = url
			// <a href='/one-fish?two=fish#red-fish-blue-fish'></a>

6. browser history与hash history
	browser history与hash history都被用于浏览器环境。
		创建history对象的方法:
			const browserHistory = createBrowserHistory()
			const hashHistory = createHashHistory()

	区别:
		最大区别在于从URL创建location的方式。
		browser history使用完整URL,而hash history只使用在#后的那部分URL。
			
7. memory 缓存所有history
	使用memory location可以在能使用JavaScript的地方随意使用。
	允许在不依赖浏览器运行的情况下测试代码	
	使用memory history会失去与地址栏的交互能力

猜你喜欢

转载自blog.csdn.net/kangkang_style/article/details/88825977