【问题标题】:REACT router cannot access params when using render()使用 render() 时,REACT 路由器无法访问参数
【发布时间】:2018-05-01 15:37:00
【问题描述】:

我是 redux 的新手,我创建了一个导航到用户编辑页面的路由,我还想使用下面的代码将 store 和 history 作为 props 传递。

<Route path="/edit/:id" render={({history}) => (
          <EditUser store={store} history={history} />
)}/>

但现在我无法访问我在 EditUser 组件中传递的参数 (:id)。当我尝试使用 this.props.match.params.id 访问时,它显示未定义,但如果我重写我的路由到

就可以了
<Route path="/edit/:id" component={EditUser}/>

但现在我认为我无法通过其他道具。

非常感谢您的帮助。

【问题讨论】:

  • 你在使用哪个&lt;Route&gt;&lt;BrowserRouter&gt; ,分享你的index.js?
  • 是的,我在 index.js 中使用

标签: reactjs react-router react-router-v4 react-props


【解决方案1】:

如果你想使用match,你必须将它传递给你的组件。

<Route path="/edit/:id" render={({history, match}) => (
  <EditUser store={store} history={history} match={match} />
)}/>

你也可以只传递所有的道具:

<Route path="/edit/:id" render={props => (
  <EditUser store={store} {...props} />
)}/>

或者你可以使用 react-redux 的 connect 函数来访问商店

<Route path="/edit/:id" component={connect(mapStateToProps)(EditUser)}/>

【讨论】:

  • 感谢这个很棒的答案,通过多种方式将 react-router 与 react-redux 连接起来。我不敢相信这在文档中不是更明显......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-13
  • 1970-01-01
  • 1970-01-01
  • 2023-03-27
  • 2016-10-07
  • 2015-05-17
  • 1970-01-01
相关资源
最近更新 更多