【问题标题】:Is there a way to restrict params to certain values while using react-router?有没有办法在使用 react-router 时将参数限制为某些值?
【发布时间】:2015-09-07 20:22:49
【问题描述】:

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

<Route name="products" path="/:type/*" handler={ ProductList } />
<Route name="generic-template" path="/*" handler={ TemplatePage } />

所以我的产品页面需要类型参数,它可以是 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' }} />
    );
  }
});

然后我为每种类型的产品使用不同的路线进行静态匹配。

有没有人知道更好的解决方案?

【问题讨论】:

    标签: javascript reactjs react-router


    【解决方案1】:

    摘自official documentation

       {/* 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}
       />
    

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

    【讨论】:

    • 魔术!完美运行。
    • :) 乐于助人
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 2020-01-10
    • 1970-01-01
    相关资源
    最近更新 更多