一個 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 的路由。