react 項目學習筆記一(react-router中的history)

react-router 中的history

eact-router 是建立在history之上的

history 一個管理js應用session會話歷史的js庫。它將不同環境(瀏覽器,node...)的變量統一成了一個簡易的API來管理歷史堆棧、導航、確認跳轉、以及sessions間的持續狀態。


//基本 使用
import { createHistory } from 'history'

const history = createHistory()

// 當前的地址
const location = history.getCurrentLocation()

// 監聽當前的地址變換
const unlisten = history.listen(location => {
  console.log(location.pathname)
})

// 將新入口放入歷史堆棧
history.push({
  pathname: '/the/path',
  search: '?a=query',

  // 一些不存在url參數上面的當前url的狀態值
  state: { the: 'state' }
})

// When you're finished, stop the listener
unlisten()

你也可以使用 history對象來的方法來改變當前的location:

  • push(location)
  • replace(location)
  • go(n)
  • goBack()
  • goForward()

一個 history 知道如何去監聽瀏覽器地址欄的變化, 並解析這個 URL 轉化爲 location 對象, 然後 router 使用它匹配到路由,最後正確地渲染對應的組件。

location對象包括:

pathname      同window.location.pathname
search        同window.location.search
state         一個捆綁在這個地址上的object對象
action        PUSH, REPLACE, 或者 POP中的一個
key           唯一ID
常用的三種history
// HTML5 history, 推薦
import createHistory from 'history/lib/createBrowserHistory'

// Hash history
import createHistory from 'history/lib/createHashHistory'

// 內存 history (如:node環境)
import createHistory from 'history/lib/createMemoryHistory'

createHashHistory

這是一個你會獲取到的默認 history ,如果你不指定某個 history (即 <Router>{/* your routes */}</Router>)。它用到的是 URL 中的 hash(#)部分去創建形如 http://example.com/#/some/path 的路由。

Hash history 是默認的,因爲它可以在服務器中不作任何配置就可以運行,並且它在全部常用的瀏覽器包括 IE8+ 都可以用。但是我們不推薦在實際生產中用到它,因爲每一個 web 應用都應該有目的地去使用createBrowserHistory。

createBrowserHistory

Browser history 是由 React Router 創建瀏覽器應用推薦的 history。它使用 History API 在瀏覽器中被創建用於處理 URL,新建一個像這樣真實的`URL example.com/some/path`

createMemoryHistory

Memory history 不會在地址欄被操作或讀取。這就解釋了我們是如何實現服務器渲染的。同時它也非常適合測試和其他的渲染環境(像 React Native )。



發佈了46 篇原創文章 · 獲贊 29 · 訪問量 25萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章