从react routers browserHistory对象获取当前页面路径

Get current page path from react-routers browserHistory object

本文关键字:当前页 路径 获取 对象 react routers browserHistory      更新时间:2023-09-26

在组件之外,我需要查询当前活动的URL。基于此,我将在body(位于react根之外)上设置一些类。

第一次尝试是使用

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

但在React Router导航时,window.location.path似乎没有更新。令人惊讶的是。

所以我想,好吧,也许我可以从浏览器历史上得到这个

import { browserHistory } from 'react-router'

但遗憾的是,我也看不到从这里读取当前页面路径的方法(这个对象似乎没有合适的API文档)

有什么建议吗?这似乎是一个简单的问题,如果window.location.pathname与历史对象保持同步,问题就会出现。

至少从2017年开始,可以通过获得位置

browserHistory.getCurrentLocation();

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

我现在知道的唯一方法是使用类似的侦听器

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

这并不理想,但即使查看了历史使用的DOMUtils库,它的getWindowPath()实现也包括路径名、搜索和哈希字符串。然而,在GitHub上为您寻找文档链接时,History似乎在大约20天前收到了v3重写,现在包含了一个可能对您有用的pathUtils模块。