react history

GitHub上history库的翻译:

  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。
    a-b-c 可以回到上一级
    默认情况下,当你点击时,会调用history.push方法进行导航。
    当使用history.push()跳转到新的location时,被跳转location被清除。

    replace:方法 用法类似push,但被跳转location不会被清除。
    a-b-c 回不到上一级 适用于登录后,不需要重新回到登页面

    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
    //

  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会失去与地址栏的交互能力

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值