Tim*_*Tim 6 javascript reactjs react-router
在我的组件之外,我需要查询当前活动的URL.基于此,我将在主体上设置一些类(在我的反应根之外).
第一次尝试是使用
//Gets an array of class names that I can add to my body tag
getClassNames(window.location.pathname);
Run Code Online (Sandbox Code Playgroud)
但是,当React Router导航时,似乎不会更新 window.location.path .令人惊讶的是.
所以我想,好吧,也许我可以从browserHistory获得这个
import { browserHistory } from 'react-router'
Run Code Online (Sandbox Code Playgroud)
但是,唉,我也看不到从这里读取当前页面路径的方法(这个对象似乎没有合适的API文档)
有小费吗?看起来像一个简单的问题,如果window.location.pathname与历史对象保持同步.
Tim*_*Tim 11
好的,至少2017年,位置可通过
browserHistory.getCurrentLocation();
const location = browserHistory.getCurrentLocation();
console.log(location);
Run Code Online (Sandbox Code Playgroud)
我现在知道这样做的唯一方法是使用像这样的监听器
import { browserHistory } from 'react-router'
browserHistory.listen(function(event) {
//manage the pathname on your own
console.log(event.pathname);
});
Run Code Online (Sandbox Code Playgroud)
不太理想,但即使在查看历史使用的DOMUtils库之后,它的getWindowPath()实现也包括路径名,搜索和哈希字符串.但是,在GitHub上为你寻找文档链接,历史似乎已经收到了大约20天前的v3重写,现在包含一个对你有用的pathUtils模块.