【问题标题】:Is there a way to use the nested route ID as a prop argument in React Router有没有办法在 React Router 中使用嵌套路由 ID 作为 prop 参数
【发布时间】:2019-12-09 13:09:03
【问题描述】:

所以基本上我有一个画廊项目数组,其中包含类“GalleryItem”对象(包含画廊名称和图像列表及其名称)。

我还有一个名为“Gallery”的组件,它将 GalleryItem 类对象作为道具并呈现它。

我想要做的是使用 .../galleries/:galleryName 导航以在单个页面内呈现特定画廊。

画廊渲染得很好,但我需要它与嵌套路线一起使用!

<Switch>
<Route path="/galleries/:name" render={(props) => <Gallery {...props} galleryItem={this.state.galleryItems[:name]} />} />
<Switch>

显然这是行不通的,所以我问它是如何完成的,如果我做错了,该怎么知道。

【问题讨论】:

  • 可以在 Gallery 组件中获取match 表单道具。

标签: javascript reactjs routes nested react-router


【解决方案1】:

Route 组件passes three props to the consuming component

  • 匹配
  • 位置
  • 历史

您想use the match prop 获取您的画廊名称:

<Switch>
  <Route
    path="/galleries/:name"
    render={props => (
      <Gallery
        {...props}
        galleryItem={this.state.galleryItems[props.match.params.name]}
      />
    )}
  />
<Switch>

【讨论】:

    【解决方案2】:

    prop 匹配将包含有关如何匹配 Route 的信息。你可以这样做:

    <Route
        path="/galleries/:name"
        exact
        render={props => 
          <Gallery {...props} galleryItem={galleryItems(props.match.path.split(':')[1])} />
        }
    
    />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      • 2018-06-26
      • 2022-01-23
      • 1970-01-01
      • 2020-06-05
      • 2016-03-06
      • 2017-11-11
      相关资源
      最近更新 更多