zoukankan      html  css  js  c++  java
  • [react-router] hashHistory 和 browserHistory 的区别

    react-router提供了三种方式来实现路由,并没有默认的路由,需要在声明路由的时候,显式指定所使用的路由。

    1.  
      //v1.x
    2.  
      <Router/>
    3.  
      //v2.0.0
    4.  
      // hash history
    5.  
      import { hashHistory } from 'react-router' <Router history={hashHistory} />

    • browserHistory
    • hashHistory
    • createMemoryHistory

    官方推荐使用browserHistory

    使用hashHistory,浏览器的url是这样的:/#/user/liuna?_k=adseis

    使用browserHistory,浏览器的url是这样的:/user/liuna

    这样看起来当然是browerHistory更好一些,但是它需要server端支持。

    使用hashHistory时,因为有 # 的存在,浏览器不会发送request,react-router 自己根据 url 去 render 相应的模块。

    使用browserHistory时,从 / 到 /user/liuna, 浏览器会向server发送request,所以server要做特殊请求,比如用的 express 的话,你需要 handle 所有的路由 app.get('*', (req, res) => { ... }),使用了 nginx 的话,nginx也要做相应的配置。

    如果只是静态页面,就不需要用browserHistory,直接hashHistory就好了。

    react router为什么推荐使用browserHistory而不推荐hashHistory?

    首先 browserHistory 其实使用的是 HTML5 的 History API,浏览器提供相应的接口来修改浏览器的历史记录;而 hashHistory 是通过改变地址后面的 hash 来改变浏览器的历史记录;

    History API 提供了 pushState() 和 replaceState() 方法来增加或替换历史记录。而 hash 没有相应的方法,所以并没有替换历史记录的功能。但 react-router 通过 polyfill 实现了此功能,具体实现没有看,好像是使用 sessionStorage。

    另一个原因是 hash 部分并不会被浏览器发送到服务端,也就是说不管是请求 http://domain.com/index.html#foo 还是 http://domain.com/index.html#bar ,服务只知道请求了 index.html 并不知道 hash 部分的细节。而 History API 需要服务端支持,这样服务端能获取请求细节。

    还有一个原因是因为有些应该会忽略 URL 中的 hash 部分,记得之前将 URL 使用微信分享时会丢失 hash 部分。

    转载于:https://www.cnblogs.com/zhangpan1244/p/6228333.html

  • 相关阅读:
    第38章 刷新令牌
    第37章 资源所有者密码验证(Resource Owner Password Validation)
    第36章 扩展授权
    第35章 秘密(secrets)
    第34章 授予类型
    node.js+ react + redux 环境搭建
    资源整理
    django form 组件插件
    django cookies与session
    django 初始命令
  • 原文地址:https://www.cnblogs.com/ygyy/p/14819717.html
Copyright © 2011-2022 走看看