不能做的是活动检查

时间:2016-04-09 15:07:29

标签: javascript reactjs react-router

我有路线

<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'));

1 个答案:

答案 0 :(得分:7)

如上所述in the docs

  

如果所有网址参数都匹配,则路由仅被视为有效,包括可选参数及其是否存在。

表示URL参数必须匹配。这就是为什么在你的例子中:

this.context.router.isActive('/catalog/:category'); // false
this.context.router.isActive('/catalog/12');        // true

您可以在location.pathname

上使用正则表达式
this.props.location.pathname.match(/^\/catalog\/\d+\/?$/);