使用可选路径AND可选参数对路由器4进行反应

And*_*uca 11 reactjs react-router

需要声明包含字符串和参数的可选路径
现在我有了这个路径

<Route exact path="/tasks/:id" render={(props) => (
  <AsyncTask {...props} profile={this.state.profile} />
)} />
Run Code Online (Sandbox Code Playgroud)

我需要

/tasks/:id/notification/:notificationId
Run Code Online (Sandbox Code Playgroud)

在哪里notification/:notificationId可选
我尝试以这种方式添加它,但它不起作用

/tasks/:id/(notification/:notificationId)?
Run Code Online (Sandbox Code Playgroud)

我需要知道我是否来自通知链接,将其标记为已读.

这很有效

/tasks/:id/(notification)?/:notificationId?
Run Code Online (Sandbox Code Playgroud)

但它没有匹配和路径 notificationId

Chr*_*ris 11

可悲的是,似乎没有办法做到这一点.理想的方法是为您的目的创建两个单独的路由.

<Route exact path="/tasks/:id" component={...} />
<Route exact path="/tasks/:id/notification/:notificationId" component={...} />
Run Code Online (Sandbox Code Playgroud)

如果您确实只需声明一个Route,则可以使用自定义正则表达式规则(参数名称声明后括在括号中的部分):

<Route exact path="/tasks/:id/:notificationId(notification/\d+)?" component={...} />
Run Code Online (Sandbox Code Playgroud)

然而!!- 请注意,该notificationId参数将包含子字符串"notification".例如,如果您有:

tasks/123/notification/456

你将有一个taskId"123"notificationId"notification/456"(整个字符串)!

也就是说,上面的路线将匹配以下路径:

  • tasks/123
  • tasks/123/notification/456

但不是:

  • tasks/123/notification
  • tasks/123/notification/abc
  • tasks/123/456

等等...


TL; DR - 您可能希望使用两个单独的路由,如上面的第一个示例所示.

  • 如果有人想知道,这不会重新安装组件,因此为同一组件定义2条路线确实没问题. (2认同)