在我的组件之外,我需要查询当前活动的URL。我将基于此在主体上设置一些类(在我的反应根之外)。
首次尝试使用
//Gets an array of class names that I can add to my body tag
getClassNames(window.location.pathname);
但是当React Router导航时,似乎window.location.path 没有更新。令人惊讶的是。
所以我想,好吧,也许我可以从browserHistory
获得这个import { browserHistory } from 'react-router'
但是,唉,我也看不到从这里读取当前页面路径的方法(这个对象似乎没有合适的API文档)
任何提示?看起来像一个简单的问题,如果window.location.pathname与历史对象保持同步的话。
答案 0 :(得分:11)
至少从2017年开始,位置可以通过
获得 browserHistory.getCurrentLocation();
const location = browserHistory.getCurrentLocation();
console.log(location);
答案 1 :(得分:7)
我现在知道的唯一方法是使用像
这样的监听器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。