有没有一种方法可以在使用react-router时将参数限制为某些值?

Ale*_*van 5 javascript reactjs react-router

我正在建立一个带有react和react-router的站点,并且我有两种不同类型的路由,例如下面的示例:

<Route name="products" path="/:type/*" handler={ ProductList } />
<Route name="generic-template" path="/*" handler={ TemplatePage } />
Run Code Online (Sandbox Code Playgroud)

因此,我的产品页面需要type参数,该参数可以是A,B或C,并且仅当类型为A,B或C时,我希望我访问的任何链接都可以匹配我的产品路线。例如:

  • / type-A / bla-bla-filter->应该加载ProductList
  • / type-B / other-params-> ProductList应该加载
  • / services / details-> TemplatePage应该加载

但是,根据我现在的情况,Products路由会匹配任何页面,因为类型只是作为斜杠后的第一个字符串进行匹配。作为一种解决方法,我尝试将我的ProductList组件包装到单独的包装器组件中,这些包装器仅发送该类型参数,如下所示:

var TypeAWrapper = React.createClass({
  render: function () {
    return (
      <ProductList params={{ splat: this.props.params.splat, type: 'A' }} />
    );
  }
});

var TypeBWrapper = React.createClass({
  render: function () {
    return (
      <ProductList params={{ splat: this.props.params.splat, type: 'B' }} />
    );
  }
});
Run Code Online (Sandbox Code Playgroud)

然后我针对具有静态匹配的每种产品使用了不同的路线。

有谁知道更好的解决方案吗?

Lan*_*nci 19

摘自官方文档

   {/* It's possible to use regular expressions to control what param values should be matched.
     * "/order/asc"  - matched
     * "/order/desc" - matched
     * "/order/foo"  - not matched*/}
   <Route
     path="/order/:direction(asc|desc)"
     component={ComponentWithRegex}
   />
Run Code Online (Sandbox Code Playgroud)

您可以将正则表达式与 Route 组件的确切道具混合使用,以避免产品始终匹配