Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何确定当前路由在React中是否处于活动状态_Javascript_Node.js_Reactjs_React Router - Fatal编程技术网

Javascript 如何确定当前路由在React中是否处于活动状态

Javascript 如何确定当前路由在React中是否处于活动状态,javascript,node.js,reactjs,react-router,Javascript,Node.js,Reactjs,React Router,react v0.14.7/react路由器:v2.0.1 我的路线设置如下: import { Router, Route, IndexRoute, hashHistory } from "react-router" ReactDOM.render( <Router history={hashHistory}> <Route path="/" component={App}> <IndexRoute component={Index}/&

react v0.14.7/react路由器:v2.0.1

我的路线设置如下:

import { Router, Route, IndexRoute, hashHistory } from "react-router"

ReactDOM.render(
  <Router history={hashHistory}>
    <Route path="/" component={App}>
      <IndexRoute component={Index}/>
      <Route path="/locations" component={Locations}/>
      <Route path="/products" component={Products}/>
    </Route>
  </Router>, 
  document.getElementById('app'));
从“react Router”导入{Router,Route,IndexRoute,hashHistory}
ReactDOM.render(
, 
document.getElementById('app');
我正在尝试在我的一个React类(使用以下API创建)中编写一个方法

导出默认类MyClass扩展React.Component{…}

…确定当前URL的路径是否为特定路由的路径

比如说。假设当前URL为
http://domain/products
然后呼叫:

isActive(“/products”)

将返回
TRUE

我知道React路由器的
链接
对象
activeClassName
。但是我需要编写一些东西,以编程的方式在不同的位置查找它,我在那里定义了
对象

查看
node\u modules/react router/
我可以看到
modules/isActive.js
满足了我的需要,但是它在
modules/index.js
中没有
export
ed,所以我假设我无法访问它


我也明白了,但我也不知道怎么称呼它?

好的,多亏了迈克·波马克斯·卡默曼,我解决了这个问题,如下所示:

已将创建类API更改为:

export default class MyClass extends React.Component {

    ...  

}
致:

并在类中添加了以下
contextTypes
定义:

export default React.createClass({

  contextTypes: {
    router: React.PropTypes.object
  },

  render(){

    console.log(this.context.router.isActive('/foo')); // Now works :)

    ...
  }

})

this.context.router.isActive
不适合你吗?@Oleg,似乎不适合。我得到一个JS控制台错误:“TypeError:this.context.router未定义”您忘记添加的极其重要的信息:react router的哪个版本?(如果是2.0,你记得吗?)对不起,是的。我使用的是react router v2.0.1使用react.PropTypes会在react的新版本中发出警告。看见
export default React.createClass({

  contextTypes: {
    router: React.PropTypes.object
  },

  render(){

    console.log(this.context.router.isActive('/foo')); // Now works :)

    ...
  }

})