我正在使用 React 和 React-router 构建一个站点,并且我有两种不同类型的路由,如下例所示:
<Route name="products" path="/:type/*" handler={ ProductList } />
<Route name="generic-template" path="/*" handler={ TemplatePage } />
因此,我的产品页面需要类型参数,可以是 A、B 或 C,并且我希望仅当类型为 A、B 或 C 时,我访问的任何链接才能匹配我的产品路线。举个例子:
但就我现在所拥有的而言,任何页面都由产品路由匹配,因为类型只是匹配斜杠后的第一个字符串。作为解决方法,我尝试将 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' }} />
);
}
});
然后我对每种类型的产品使用不同的路线进行静态匹配。
有人知道更好的解决方案吗?
摘自官方文档
{/* 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 组件的精确属性混合,以避免产品始终匹配
我从这里找到了这个解决方案:https://github.com/remix-run/react-router/discussions/9844#discussioncomment-4692242
适用于 React Router v6
函数 LangParamValidator 是示例。您可以使用这种方法来实现您的验证。
<Routes>
<Route path="/" element={<Dashboard />} />
<Route path=":lang" element={<LangParamValidator />}>
<Route index element={<RouteWithLangParam />} />
<Route>
<Route path="*" element={<NotFound />} />
</Routes>
function LangParamValidator() {
const { lang } = useParams<'lang'>()
if (lang && ALLOWED_LANGS.incldues(lang)) {
return <Outlet />
}
return <Navigate path="/" replace />
}