Javascript 从浏览器历史对象获取当前页面路径
在我的组件之外,我需要查询当前的活动URL。基于此,我将在body上设置一些类(在我的react根之外) 第一次尝试是使用Javascript 从浏览器历史对象获取当前页面路径,javascript,reactjs,react-router,Javascript,Reactjs,React Router,在我的组件之外,我需要查询当前的活动URL。基于此,我将在body上设置一些类(在我的react根之外) 第一次尝试是使用 //Gets an array of class names that I can add to my body tag getClassNames(window.location.pathname); 但当React路由器导航时,window.location.path似乎没有更新。是的 所以我想,好吧,也许我可以从browserHistory那里得到这个 import
//Gets an array of class names that I can add to my body tag
getClassNames(window.location.pathname);
但当React路由器导航时,window.location.path似乎没有更新。是的
所以我想,好吧,也许我可以从browserHistory那里得到这个
import { browserHistory } from 'react-router'
但是遗憾的是,我也看不到一种从这里读取当前页面路径的方法(这个对象似乎没有像样的API文档)
有什么建议吗?这似乎是一个简单的问题,如果window.location.pathname与历史记录对象保持同步,则会出现此问题。我现在知道的唯一方法是使用类似的侦听器
import { browserHistory } from 'react-router'
browserHistory.listen(function(event) {
//manage the pathname on your own
console.log(event.pathname);
});
这并不理想,但即使查看了历史使用的DOMUtils库,它的getWindowPath()实现也包括路径名、搜索和哈希字符串。然而,在GitHub上为您寻找文档链接时,历史记录似乎在大约20天前收到了一个v3重写,现在包含了一个可能对您有用的文档链接。至少在2017年确定,位置可通过
browserHistory.getCurrentLocation()代码>
反应-router@3.2.0应该调用location.pathname
路由器v4怎么样?
const location = browserHistory.getCurrentLocation();
console.log(location);