我正在使用 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 应该加载
但就我现在所拥有的而言,任何页面都与产品路由匹配,因为类型只是匹配斜杠后的第一个字符串。作为解决方法,我尝试将 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' }} />
);
}
});
然后我对每种类型的产品使用不同的路线进行静态匹配。
有谁知道更好的解决方案?
摘自官方文档 https://reacttraining.com/react-router/web/example/url-params
{/* 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 组件的精确属性混合,以避免产品始终匹配
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)