2017-07-28 66 views
1

我希望能夠創建一個鏈接到我在同一條路線,除了改變一些參數陣營路由器:改變單一的參數,URL

在我的網站上,我決定建立一個像這樣的網址:/list/:page(\d+)?/:filter?。現在,在我的組件中,我可以訪問match(使用withRouter HOC)。在我的情況下,它包含

{ 
    isExact: true 
    params: {page: "3", filter: "duckbitt"} 
    path: "/listing/:page(\d+)?/:filter?" 
    url: "/listing/3/duckbitt" 
} 

這是非常好的,因爲我有params和路徑。 現在,這引發了2個問題:

  1. 有沒有針對這種情況的react-router builtin解決方案?
  2. 如果沒有,是否有可能的解決方案使用path-to-regexp,或者我應該使用天真的搜索和替換?

謝謝

回答

1

當然張貼問題之後的解決方案出現。

import pathToRegexp from 'path-to-regexp'; 
// (...) 
const toPath = pathToRegexp.compile(match.path); 
const newPath = toPath({ ...match.params, page: 666 }); 
console.log(newPath); // "/listing/666/duckbitt"