2016-03-24 109 views
4

在我的組件之外,我需要查詢當前的活動URL。我將在此基礎上在身體上設置一些類(這在我的反應根之外)。從react-routers獲取當前頁面路徑browserHistory對象

第一次嘗試使用

//Gets an array of class names that I can add to my body tag 
getClassNames(window.location.pathname); 

但當陣營路由器導航似乎window.location.path 不更新。令人驚訝的是。

所以我就想,好吧,也許我可以從browserHistory

import { browserHistory } from 'react-router' 

得到這個但是,唉,我看不到任何方式(沒有像樣的API文檔似乎存在從這裏閱讀當前頁面路徑對於這個對象)

任何提示?看起來像一個簡單的問題,這將是如果window.location.pathname保持與歷史對象同步。

回答

5

好爲2017至少,位置經由

browserHistory.getCurrentLocation();

const location = browserHistory.getCurrentLocation(); 
console.log(location); 
+2

在[email protected]應該調用'可用location.pathname' –

5

我知道現在要做此問題的唯一方法是使用一個聽衆喜歡

import { browserHistory } from 'react-router' 
browserHistory.listen(function(event) { 
    //manage the pathname on your own 
    console.log(event.pathname); 
}); 

並不理想,但即使看着被歷史所使用的DOMUtils庫後,其執行getWindowPath()的包括路徑名,搜索和散列字符串。然而,在GitHub上爲你尋找一個文檔鏈接,歷史似乎已經在大約20天前獲得了v3重寫,現在包含了對你有用的pathUtils module