gpt4 book ai didi

javascript - 不能做 isActive 检查

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:31:37 25 4
gpt4 key购买 nike

我有路线

<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+\/?$/);

关于javascript - 不能做 isActive 检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36518600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com