【发布时间】: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