【问题标题】:How to use ownProps on a Class Based Component (react-redux)如何在基于类的组件上使用 ownProps (react-redux)
【发布时间】: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-routerwihRouter HOC
  • 感谢您指出这一点,我正在使用 react-router-dom。我会把它添加到帖子中,谢谢。

标签: javascript reactjs react-redux


【解决方案1】:

您需要使用 withRouter HOC of react-router 包装连接的组件

export default withRouter(connect(mapStateToProps)(Destination))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-18
    • 2019-11-29
    • 2021-05-25
    • 1970-01-01
    • 2022-06-12
    • 2022-12-09
    • 1970-01-01
    • 2023-03-31
    相关资源
    最近更新 更多