react-router-dom之 history用法


根據環境的需要,我們提供了創建歷史對象的3種不同方法:

createBrowserHistory: 用於支持HTML5歷史API的現代Web瀏覽器(參見跨瀏覽器兼容性)

createHashHistory: 用於希望將位置存儲在當前URL的哈希中以避免在頁面重新加載時將其發送到服務器的情況

createMemoryHistory: 用作引用實現,也可用於非DOM環境,如對本地或測試的反應。

根據要用於跟蹤歷史記錄的方法,您將 import (or require,如果使用commonjs)其中一個方法。

1.基本用法

import { createBrowserHistory } from 'history';

const history = createBrowserHistory();

// 獲取當前 location
const location = history.location;

// 監聽當前 location改變
const unlisten = history.listen((location, action) => {
  // location is an object like window.location
  console.log(action, location.pathname, location.state);
});

//使用push、replace和go導航
history.push('/home', { some: 'state' });

//要停止偵聽,請調用從listen()返回的函數
unlisten();

每個創建方法所采用的選項及其默認值包括:

createBrowserHistory({
  basename: '', // The base URL of the app (see below)
  forceRefresh: false, // Set true to force full page refreshes
  keyLength: 6, // The length of location.key
  // A function to use to confirm navigation with the user (see below)
  getUserConfirmation: (message, callback) => callback(window.confirm(message))
});

createHashHistory({
  basename: '', // The base URL of the app (see below)
  hashType: 'slash', // The hash type to use (see below)
  // A function to use to confirm navigation with the user (see below)
  getUserConfirmation: (message, callback) => callback(window.confirm(message))
});

createMemoryHistory({
  initialEntries: ['/'], // The initial URLs in the history stack
  initialIndex: 0, // The starting index in the history stack
  keyLength: 6, // The length of location.key
  // A function to use to confirm navigation with the user. Required
  // if you return string prompts from transition hooks (see below)
  getUserConfirmation: null
});

2.屬性

每個history對象都有以下屬性:

  • history.length - 歷史堆棧中的條目數
  • history.location - 當前的 location (見下文)
  • history.action - 當前導航操作(見下文)

此外,createMemoryHistory 提供了history.indexhistory.entries屬性,這些屬性允許您檢查歷史堆棧。

3.監聽

可以使用history.listen監聽當前位置的更改:

history.listen((location, action) => {
  console.log(
    `The current URL is ${location.pathname}${location.search}${location.hash}`
  );
  console.log(`The last navigation action was ${action}`);
});

location對象實現 window.location 接口的子集,包括:

  • location.pathname - The path of the URL
  • location.search - The URL query string
  • location.hash - The URL hash fragment

Location還可以具有以下屬性:

  • location.state - 當前location不存在於URL中的一些額外狀態 (createBrowserHistory、createMemoryHistory支持該屬性)
  • location.key - 表示當前loaction的唯一字符串 (createBrowserHistory、createMemoryHistory支持該屬性)

回調函數返回的參數action是push、replace或pop,具體取決於用戶如何到達當前url。

取消監聽:
使用history.listen附加偵聽器時,它返回一個可用於刪除偵聽器的函數,然后可以在清理邏輯中調用該函數:

const unlisten = history.listen(myListener);
// ...
unlisten();

 

4.導航

history對象可以使用以下方法以編程方式更改當前位置:

  • history.push(path, [state])
  • history.replace(path, [state])
  • history.go(n)
  • history.goBack()
  • history.goForward()
  • history.canGo(n) (only in createMemoryHistory)

使用push或replace時,可以將url路徑和狀態指定為單獨的參數,也可以將object等單個位置中的所有內容作為第一個參數:

  • 一個url路徑
  • 一個路徑對象 { pathname, search, hash, state }
// Push a new entry onto the history stack.
history.push('/home');

// Push a new entry onto the history stack with a query string
// and some state. Location state does not appear in the URL.
history.push('/home?the=query', { some: 'state' });

// If you prefer, use a single location-like object to specify both
// the URL and state. This is equivalent to the example above.
history.push({
  pathname: '/home',
  search: '?the=query',
  state: { some: 'state' }
});

// Go back to the previous history entry. The following
// two lines are synonymous.
history.go(-1);
history.goBack();

注意:state僅在createBrowserHistory和createMemoryHistory中得到支持。

5.blocking transitions 阻塞過渡

history允許您在location監聽觸發之前注冊一個提示信息呈現給用戶。

// 注冊一個簡單的提示消息,在用戶離開當前頁面之前,該消息將顯示給用戶。
const unblock = history.block('Are you sure you want to leave this page?');

// 或者在需要時使用返回消息的函數。
history.block((location, action) => {
  //location和action參數指示我們要轉換到的位置以及如何到達那里。

  //一個常見的用例是防止用戶在有表單尚未提交時離開頁面。
  if (input.value !== '') return 'Are you sure you want to leave this page?';
});

// 要停止blocking transitions,請調用block()返回的函數。
unblock();

注意:如果使用createMemoryHistory的這個特性的話,您需要提供一個getUserConfirmation函數(請參閱下文)。

自定義確認對話框
默認情況下,window.confirm用於向用戶顯示提示消息。如果需要重寫此行為(或者如果您使用的是createMemoryHistory,它不假定DOM環境),則在創建歷史對象時提供getUserConfirmation。

const history = createHistory({
  getUserConfirmation(message, callback) {
    // 向用戶顯示一些自定義對話框並調用callback(true)繼續傳輸,或調用callback(false)中止傳輸。
  }
});

6.其它

1. 使用basename
如果應用程序中的所有URL都與其他“base”URL相關,請使用 basename 選項。此選項將給定字符串添加到您使用的所有URL的前面。

const history = createHistory({
  basename: '/the/base'
});

history.listen(location => {
  console.log(location.pathname); // /home
});

history.push('/home'); // URL is now /the/base/home

注意在createMemoryHistory中不支持basename屬性。

2. 在CreateBrowserHistory中強制刷新整頁
默認情況下,createBrowserHistory使用HTML5 pushStatereplaceState來防止在導航時從服務器重新加載整個頁面。如果希望在url更改時重新加載,請使用forcerefresh選項。

const history = createBrowserHistory({
  forceRefresh: true
});

3.修改createHashHistory中的Hash類型
默認情況下,createHashHistory在基於hash的URL中使用'/'。可以使用hashtype選項使用不同的hash格式。

const history = createHashHistory({
  hashType: 'slash' // the default
});

history.push('/home'); // window.location.hash is #/home

const history = createHashHistory({
  hashType: 'noslash' // Omit the leading slash
});

history.push('/home'); // window.location.hash is #home

const history = createHashHistory({
  hashType: 'hashbang' // Google's legacy AJAX URL format
});

history.push('/home'); // window.location.hash is #!/home










 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM