[英]How to use ownProps on a Class Based Component (react-redux)
I have been using the react-redux packages connect function on functional components to get a URL parameter and I love using that, however now on a Class-based component, I am not getting the URL parameters. 我一直在使用React-redux软件包的功能组件上的connect函数来获取URL参数,但我喜欢使用它,但是现在在基于类的组件上,我没有得到URL参数。
Am I missing something? 我想念什么吗? I have tried searching for a similar topic on here, but I'm not certain which of the solutions are applicable to my problem.
我曾尝试在此处搜索类似的主题,但不确定哪种解决方案适用于我的问题。 I hope I'm missing something simple, as the ownProps on functional components is so convenient to use.
我希望我缺少一些简单的东西,因为功能组件上的ownProps非常方便使用。
Router: (I am just showing the one path here. I am using react-router-dom ) 路由器:(我只是在这里显示一个路径。我正在使用react-router-dom )
<Route path="/destination/:id" component={Destination}/>
Component: 零件:
import React, { Component } from 'react'
import { connect } from 'react-redux'
class Destination extends Component {
state = {
}
render() {
return (
<div>
The ID is: {this.props.id}
</div>
)
}
}
const mapStateToProps = (state, ownProps) => {
const id = ownProps.match.params.id
return {
id
}
}
export default connect(mapStateToProps)(Destination)
When I go to the URL, I get this error: 当我转到URL时,出现以下错误:
TypeError: Cannot read property 'params' of undefined TypeError:无法读取未定义的属性“ params”
Thank you! 谢谢!
您将需要使用react-router
的withRouter
HOC包装连接的组件
export default withRouter(connect(mapStateToProps)(Destination))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.