【发布时间】:2019-11-13 01:22:34
【问题描述】:
我一直在功能组件上使用 react-redux 包连接函数来获取 URL 参数,我喜欢使用它,但是现在在基于类的组件上,我没有获取 URL 参数。
我错过了什么吗?我曾尝试在这里搜索类似的主题,但我不确定哪些解决方案适用于我的问题。我希望我遗漏了一些简单的东西,因为函数组件上的 ownProps 使用起来非常方便。
Router:(我这里只显示一条路径。我正在使用 react-router-dom)
<Route path="/destination/:id" component={Destination}/>
组件:
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)
当我转到 URL 时,我收到此错误:
TypeError: 无法读取未定义的属性“参数”
谢谢!
【问题讨论】:
-
不确定您使用的是什么版本的
react-router,但我认为您应该使用react-router的wihRouterHOC -
感谢您指出这一点,我正在使用 react-router-dom。我会把它添加到帖子中,谢谢。
标签: javascript reactjs react-redux