我试图不使用:if(window.location)来访问我当前的路径。
我正在研究已定义路由器的代码,并且已经编写了该组件。我试图从组件中访问路由器信息,因为我需要根据路由应用类名。
以下是路由器的外观:
export const createRoutes = (dispatch, getState) => (
<Route component={AppLayout} >
<Route path="/" component={Home} onEnter={(nextState, replaceState) => {
console.log('on Enter / = ', nextState);
nextState.test = 'aaaa'; //can't seem to pass states here....
}} />
然后在我的组件中:
render() {
//I want to access my super router or location . in fact
// I just want to know if currentURl === '/'
//and after reading the react-router doc 5 times - my head hurts
// but I still hope to get an answer here before putting a window.location
}
`
答案 0 :(得分:3)
根据您使用的React路由器的版本,您可以访问组件context
上提供的不同对象。
MyComponent.contextTypes = {
location: React.PropTypes.object
}
这将使您能够执行以下操作
render() {
if (this.context.location.pathname === '/') {
return <h1>Index</h1>;
} else {
return <h2>Not index</h2>;
}
}