如何使用React Router修改作为道具发送的路由参数?

时间:2016-08-10 10:52:33

标签: javascript reactjs react-router router

我有一个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>

这可能吗?

2 个答案:

答案 0 :(得分:2)

您应该使用更高阶的组件。

您可以使用mapProps中的recompose高阶组件:

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>

答案 1 :(得分:1)

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>