不能做是活动检查

fan*_*tua 3 javascript reactjs react-router

我有路线

<Route path="/catalog/:category" component={CatalogList} />
Run Code Online (Sandbox Code Playgroud)

例如,当我在页面/ catalog/10上时,我尝试检查该路由是否处于活动状态

this.context.router.isActive('/catalog/:category')
Run Code Online (Sandbox Code Playgroud)

但我总是假的.怎么检查这个?

例:

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'));
Run Code Online (Sandbox Code Playgroud)

Von*_*onD 7

正如文档中所述

如果所有URL参数都匹配,则路由仅被视为活动路由,包括可选参数及其是否存在.

这意味着URL参数必须匹配.这就是为什么在你的例子中:

this.context.router.isActive('/catalog/:category'); // false
this.context.router.isActive('/catalog/12');        // true
Run Code Online (Sandbox Code Playgroud)

你可以使用正则表达式 location.pathname

this.props.location.pathname.match(/^\/catalog\/\d+\/?$/);
Run Code Online (Sandbox Code Playgroud)