2016-03-24 44 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