【问题标题】:How do I modify the route parameters sent as props with React Router?如何使用 React Router 修改作为 props 发送的路由参数?
【发布时间】:2016-12-16 17:12:49
【问题描述】:

我有一个 React Router,其路由如下:

<Router history={history}>
  <Route path='/' component={App} />
  <Route path='/:fileType/:fileId' component={App} />
</Router>

这会将道具放入我的App,如下所示:

{
  fileType: 'whatever', 
  fileId: 'ABC5734'
}

但是,我已经设计了我的组件,因此它需要这种格式:

{
  file: {
    type: 'whatever', 
    id: 'ABC5734'
  }
}

因此,我想在将路径道具发送到组件之前对其进行转换。像这样的:

<Router history={history}>
  <Route path='/' component={App} />
  <Route 
    path='/:fileType/:fileId' 
    component={(props) => <App file={{type: props.fileType, id: props.fileId}} />} />
</Router>

这可能吗?

【问题讨论】:

    标签: javascript reactjs react-router router


    【解决方案1】:

    您应该使用高阶组件。

    您可以使用来自recomposemapProps 高阶组件:

    import mapProps from 'recompose/mapProps'
    
    <Router history={history}>
      <Route path='/' component={App} />
      <Route 
        path='/:fileType/:fileId' 
        component={mapProps(({ params: { fileType, fileId } }) => ({
            fileType,
            fileId
        }))(App)}/>
    </Router>
    

    【讨论】:

      【解决方案2】:

      React-router 在this.props.params 下发送路由参数。因此,请更正您的代码。

      <Router history={history}>
        <Route path='/' component={App} />
        <Route 
          path='/:fileType/:fileId' 
          component={(props) => <App file={{type: props.params.fileType, id: props.params.fileId}} />} />
      </Router>
      

      【讨论】:

      • (props) =&gt; &lt;App file={{type: props.params.fileType, id: props.params.fileId}} /&gt; 本身就是一个哑组件,以 App 组件为子组件。
      猜你喜欢
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      • 2016-09-09
      • 2015-10-30
      • 1970-01-01
      • 2020-04-06
      • 2016-09-05
      • 1970-01-01
      相关资源
      最近更新 更多