不能做 isActive 检查
Can't do isActive check
我有路线
<Route path="/catalog/:category" component={CatalogList} />
例如,当我在页面 /catalog/10 上时,我尝试检查该路由是否处于活动状态
this.context.router.isActive('/catalog/:category')
但我总是出错。如何检查?
示例:
const Test = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
render() {
console.log(this.props.location.pathname); // /catalog/12
console.log(this.context.router.isActive('/catalog/:category')); // false (need true)
console.log(this.context.router.isActive('/catalog/12')); //true
return <Link to="/catalog/12">Lets test</Link>;
}
});
render((
<div>
<Router history={browserHistory}>
<Route path="/catalog/:category" component={Test} />
<Route path="/" component={Test} />
</Router>
</div>
), document.getElementById('app'));
如前所述in the docs
A route is only considered active if all the URL parameters match, including optional parameters and their presence or absence.
这意味着 URL 参数必须匹配。这就是为什么在你的例子中:
this.context.router.isActive('/catalog/:category'); // false
this.context.router.isActive('/catalog/12'); // true
您可以在 location.pathname
上使用正则表达式
this.props.location.pathname.match(/^\/catalog\/\d+\/?$/);
我有路线
<Route path="/catalog/:category" component={CatalogList} />
例如,当我在页面 /catalog/10 上时,我尝试检查该路由是否处于活动状态
this.context.router.isActive('/catalog/:category')
但我总是出错。如何检查?
示例:
const Test = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
render() {
console.log(this.props.location.pathname); // /catalog/12
console.log(this.context.router.isActive('/catalog/:category')); // false (need true)
console.log(this.context.router.isActive('/catalog/12')); //true
return <Link to="/catalog/12">Lets test</Link>;
}
});
render((
<div>
<Router history={browserHistory}>
<Route path="/catalog/:category" component={Test} />
<Route path="/" component={Test} />
</Router>
</div>
), document.getElementById('app'));
如前所述in the docs
A route is only considered active if all the URL parameters match, including optional parameters and their presence or absence.
这意味着 URL 参数必须匹配。这就是为什么在你的例子中:
this.context.router.isActive('/catalog/:category'); // false
this.context.router.isActive('/catalog/12'); // true
您可以在 location.pathname
this.props.location.pathname.match(/^\/catalog\/\d+\/?$/);