最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get current page path from react-routers browserHistory object - Stack Overflow

programmeradmin7浏览0评论

Outside of my ponents I need to query the current active URL. I'm going to set some classes on the body ( which is outside my react root ) based on this.

First attempt was to use

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

But it seems window.location.path isn't updated when React Router navigates. Surprising yes.

So I thought, ok maybe I can get this from browserHistory

import { browserHistory } from 'react-router'

But alas, I can't see a way to read the current page path from here either ( no decent API documentation seems to exist for this object)

Any tips? Seems like a simple problem, and it would be if window.location.pathname stayed in sync with the history object.

Outside of my ponents I need to query the current active URL. I'm going to set some classes on the body ( which is outside my react root ) based on this.

First attempt was to use

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

But it seems window.location.path isn't updated when React Router navigates. Surprising yes.

So I thought, ok maybe I can get this from browserHistory

import { browserHistory } from 'react-router'

But alas, I can't see a way to read the current page path from here either ( no decent API documentation seems to exist for this object)

Any tips? Seems like a simple problem, and it would be if window.location.pathname stayed in sync with the history object.

Share Improve this question edited Mar 30, 2016 at 0:20 Nonemoticoner 6485 silver badges14 bronze badges asked Mar 24, 2016 at 2:01 TimTim 4,6615 gold badges39 silver badges44 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 13

Ok as of 2017 at least, location is available via

browserHistory.getCurrentLocation();

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

The only way I know to do this right now is to use a listener like

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

Not ideal, but even after looking at the DOMUtils library used by history, its implementation of getWindowPath() includes the pathname, search, and hash strings. However, looking for a docs link for you on GitHub, History seems to have received a v3 rewrite as of ~20 days ago and now includes a pathUtils module that may be useful to you.

发布评论

评论列表(0)

  1. 暂无评论