【问题标题】:How to render nested routes with multiple optional params and path placeholders?如何使用多个可选参数和路径占位符渲染嵌套路由?
【发布时间】:2019-06-25 19:47:52
【问题描述】:

我一直在尝试使用react-router 定义一系列带有可选参数的嵌套组件/路由,但也由路径占位符分隔。

/list
/list/1
/list/items
/list/1/items
/list/1/items/1

我假设两个<Route> 路径类似于:

/list/:listId?
and
`${match.url}`/items/:itemId?`

但是,唉.."items" 总是最终被接受为 listId 参数,因此,/items 的子路由永远不会匹配。

我在这里编写了一个通用示例(没有完成解决方案):https://stackblitz.com/edit/nesting-w-optional-params-react-router

我在互联网上看到了/root/:id1?/:id2? 的示例,但我在参数之间有一个占位符的地方没有看到我正在尝试做的事情:/root/:id1/placeholder/:id2

这可以用react-router v4+ 做吗??

【问题讨论】:

    标签: react-router react-router-v4 react-router-dom path-to-regexp


    【解决方案1】:

    想出一个利用 RR 的 children 模式的解决方案,总是渲染嵌套的路由/组件,然后在组件内部直接使用 path-to-regexp 进行路由匹配并获取相关的路由参数来自props.location.pathname

    相关代码:

    render() {
        const pathRe = new PathToRegexp('/foo/:fooId?/bar/:barId?')
        const match = pathRe.match(this.props.location.pathname)
        if (!match) {
          return null
        }
        const barId = (this.props.match && this.props.match.params.barId) || match.barId
        return <h1>Bar <em>{barId}</em></h1>
      }
    

    https://stackblitz.com/edit/nesting-w-optional-params-react-router-solution

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-06
      • 1970-01-01
      • 1970-01-01
      • 2019-01-12
      • 2014-10-05
      • 2021-12-28
      相关资源
      最近更新 更多