问题描述
我想声明一个带有可选路径参数的路径,因此当我将它添加到页面以做一些额外的事情时(例如填充一些数据):
I want to declare a path with an optional path parameter, hence when I add it the page to do something extra (e.g. fill some data):
http://localhost/app/path/to/page http://localhost/app/path/to/page/pathParam
在我的反应路由器中,我有以下路径,以支持这两个选项(这是一个简化示例):
In my react router I have the following paths, in order to support the two options (this is a simplified example):
<Router history={history}>
<Route path="/path" component={IndexPage}>
<Route path="to/page" component={MyPage}/>
<Route path="to/page/:pathParam" component={MyPage}/>
</Route>
</Router>
我的问题是,我们可以在一个路线中声明它吗?如果我只添加了第二行,那么没有找到没有参数的路由.
My question is, can we declare it in one route? If I add only the second row then the route without the parameter is not found.
编辑#1:
在这里提到的关于以下语法的解决方案对我不起作用,是不是合适的?它是否存在于文档中?
The solution mentioned here about the following syntax did not work for me, is it a proper one? Does it exist in the documentation?
<Route path="/product/:productName/?:urlID?" handler={SomeHandler} />
我的 react-router 版本是:1.0.3
My react-router version is: 1.0.3
推荐答案
您发布的编辑对旧版本的 React-router (v0.13) 有效,不再起作用.
The edit you posted was valid for an older version of React-router (v0.13) and doesn't work anymore.
从 1.0.0
版本开始,您定义可选参数:
Since version 1.0.0
you define optional parameters with:
<Route path="to/page(/:pathParam)" component={MyPage} />
对于多个可选参数:
<Route path="to/page(/:pathParam1)(/:pathParam2)" component={MyPage} />
您使用括号 (
)
来包裹路由的可选部分,包括前导斜线 (/
).查看路由匹配指南 官方文档页面.
You use parenthesis (
)
to wrap the optional parts of route, including the leading slash (/
). Check out the Route Matching Guide page of the official documentation.
注意: :paramName
参数匹配直到下一个 /
的 URL 段,?
或 #
.有关路径和参数的更多信息,请在这里阅读更多内容.
Note: The :paramName
parameter matches a URL segment up to the next /
, ?
, or #
. For more about paths and params specifically, read more here.
React Router v4 与 v1-v3 有着根本的不同,可选的路径参数没有在 中明确定义官方文档.
React Router v4 is fundamentally different than v1-v3, and optional path parameters aren't explicitly defined in the official documentation either.
相反,您被指示定义一个 path
参数,该参数正则表达式路径 理解.这允许在定义路径时具有更大的灵活性,例如重复模式、通配符等.因此,要将参数定义为可选参数,请添加尾随问号 (?
).
Instead, you are instructed to define a path
parameter that path-to-regexp understands. This allows for much greater flexibility in defining your paths, such as repeating patterns, wildcards, etc. So to define a parameter as optional you add a trailing question-mark (?
).
因此,要定义可选参数,您需要:
As such, to define an optional parameter, you do:
<Route path="/to/page/:pathParam?" component={MyPage} />
对于多个可选参数:
<Route path="/to/page/:pathParam1?/:pathParam2?" component={MyPage} />
注意: React Router v4 与 (在此处阅读更多信息).改用 v3 或更早版本(推荐 v2).
Note: React Router v4 is incompatible with react-router-relay (read more here). Use version v3 or earlier (v2 recommended) instead.
这篇关于使用可选路径参数反应路由器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!