【问题标题】:Multiple params with React Router使用 React Router 的多个参数
【发布时间】:2016-10-08 08:40:02
【问题描述】:

我使用 React 15.0.2 和 React Router 2.4.0。 我想将多个参数传递给我的路线,但我不确定如何以最好的方式做到这一点:

<Route name="User" path="/user" component={UserPage}>   
    <Route name="addTaskModal" path="/user/manage:id" component={ManageTaskPage} />
</Route>

想要的是这样的:

 <Route name="User" path="/user" component={UserPage}>  
    <Route name="addTaskModal" path="/user/manage:id:type" component={ManageTaskPage} />
</Route>

【问题讨论】:

  • 也许像path="/user/manage/:id/:type" ?
  • 好的,谢谢您的回复。我只是在想那个。还没喝我的咖啡。需要启动我的大脑。

标签: reactjs react-router


【解决方案1】:

正如@alexander-t 提到的:

path="/user/manage/:id/:type"

如果您想让它们保持可选:

path="/user/manage(/:id)(/:type)"

反应路由器 v4

React Router v4 与 v1-v3 不同,可选路径参数未在 documentation 中明确定义。

相反,系统会指示您定义path-to-regexp 可以理解的路径参数。这为定义路径提供了更大的灵活性,例如重复模式、通配符等。因此,要将参数定义为可选参数,请添加尾随问号 (?)。

所以,要定义可选参数,你可以这样做:

path="/user/manage/:pathParam1?/:pathParam2?"

<Route path="/user/manage/:pathParam1?/:pathParam2?" component={MyPage} />

然而,强制参数在 V4 中仍然相同:

path="/user/manage/:id/:type"

要访问 PathParam 的值,您可以:

this.props.match.params.pathParam1

【讨论】:

  • 简单说明——在 React Router 4 中,可选参数如下所示:/user/manage/:id?/:type?
  • 能否请您告诉我如何使用多个命名参数指定路径?像这样:/route?param1=val1&amp;param2=val2
  • @rehman_00001 我得到了相同问题的解决方案。 Here it is explained really well
  • 地址栏的参数可以隐藏吗?谢谢
【解决方案2】:

对于可选的参数字段,由于某种原因,在大括号 () 内的冒号之前没有斜杠,它可以正常工作。反应路由器 2.6x

【讨论】:

    【解决方案3】:

    试试这个

    <Route name="User" path="/user" component={UserPage}>  
      <Route name="addTaskModal" path="/user/manage/:id/:type" component={ManageTaskPage} />
    </Route>
    

    【讨论】:

      【解决方案4】:
      <Route path="/:category/:id" exact component={ItemDetails} />
      

      在组件中,使用useParams from react-router-dom

      import { useParams } from 'react-router-dom'
      export default function ItemDetails(props) {
      
      const {id, category} = useParams();
      return (
          <div className="">
              {id}
              {category}
          </div>
      )
      

      这是解决方案,不使用props 并使用路由库。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-14
        • 2019-09-12
        • 2022-07-21
        • 2019-11-19
        • 2017-09-20
        • 1970-01-01
        • 2020-11-28
        • 1970-01-01
        相关资源
        最近更新 更多