【问题标题】:Not getting props from child component in Redux没有从 Redux 中的子组件获取道具
【发布时间】:2020-05-15 05:00:13
【问题描述】:

我想在子组件中从 Redux 获取 props。但是 {this.props} 是空对象。我正在使用 react-redux connect 来获取道具。它在父组件中工作,我们可以传递给子组件以获取道具,但我需要从子组件获取

登录

```import React, { Component } from 'react'
import { Test } from './Test'

export default class Login extends Component {
    render() {
        return (
            <div>
                <Test hi=""/>
            </div>
        )
    }
}```

测试

import React, { Component } from 'react'
import { connect } from 'react-redux'

export class Test extends Component {
    render() {
        console.log(this.props)
        return (
            <div>
                vddfff
            </div>
        )
    }
}

const mapStateToProps = (state) => ({

})

const mapDispatchToProps = (dispatch) => {
    return {
        selectedData: (val) => {
            console.log("object")
        }
    }
}
export default connect(mapStateToProps, mapDispatchToProps)(Test)

【问题讨论】:

  • 因为你错过了constructor(props) { super() }。有一个很好的解释overreacted.io/why-do-we-write-super-props
  • 你的 props 对 redux 没有任何作用。
  • @demkovych 我添加了构造函数。但还是一样。还有一件事我可以看到 this.props.hi 从父母到孩子,但不是 this.props.selectedData
  • 只需使用const mapDispatchToProps = { selectedData: selectedDataAction };,其中selectedDataAction 是您的操作(来自redux)
  • 您可能想在selectedData 方法的主体中使用dispatch

标签: javascript reactjs redux react-redux


【解决方案1】:

这里的问题是您正在尝试使用您编写的测试组件,而不是由connect()react-redux 返回的高阶组件 您不需要导出 Test 类。

在 login.js 文件中,使用

import Test from './Test'

而不是

import {Test} from './Test'

在这里查看它的实际应用。 https://codesandbox.io/s/sample-test-app-q5srf

【讨论】:

    【解决方案2】:

    您使用了错误的组件。登录时需要导入:

    import Test from './Test'
    

    您导入的测试未连接到 redux(推送 redux 道具)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 1970-01-01
      • 2019-05-17
      • 2019-01-30
      • 1970-01-01
      • 2018-08-21
      相关资源
      最近更新 更多