一个 history 知道如何去监听浏览器地址栏的变化, 并解析这个 URL 转化为 location 对象, 然后 router 使用它匹配到路由,最后正确地渲染对应的组件。
常用的 history 有三种形式
browserHistory
创建一个像example.com/some/path这样真实的 URL 。
每一个 web 应用都应该渴望使用 browserHistory ?
1、比较真实的URL
2、browserHistory 其实使用的是 HTML5 的 History API,浏览器提供相应的接口来修改浏览器的历史记录;而 hashHistory 是通过改变地址后面的 hash 来改变浏览器的历史记录
3、History API 提供了 pushState() 和 replaceState() 方法来增加或替换历史记录。而 hash 没有相应的方法,所以并没有替换历史记录的功能。但 react-router 通过 polyfill 实现了此功能,具体实现没有看,好像是使用 sessionStorage。
4、有些应该会忽略 URL 中的 hash 部分,记得之前将 URL 使用微信分享时会丢失 hash 部分
服务器配置坑
express
const express = require('express')
const path = require('path')
const port = process.env.PORT || 8080
const app = express()
// 通常用于加载静态资源
app.use(express.static(__dirname + '/public'))
// 在你应用 JavaScript 文件中包含了一个 script 标签
// 的 index.html 中处理任何一个 route
app.get('*', function (request, response){
response.sendFile(path.resolve(__dirname, 'public', 'index.html'))
})
app.listen(port)
nginx
location / {
try_files $uri $uri/ /index.html;
}
Apache
创建一个.htaccess文件在你的文件根目录下:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.html$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.html [L]
</IfModule>
hashHistory
Hash history 使用 URL 中的 hash(#)部分去创建形如 example.com/#/some/path 的路由。
转载于:https://blog.51cto.com/xhtml/1945928
本文详细解释了浏览器历史记录管理中的两种方式:browserHistory和hashHistory。browserHistory使用真实URL和HTML5 History API来更新历史记录,而hashHistory则利用URL的hash部分。此外还介绍了如何在Express、Nginx和Apache等服务器环境中正确配置以支持这两种历史记录管理。
1万+

被折叠的 条评论
为什么被折叠?



