初次学react,我在this.props中获取不到dispatch方法。为什么
原因在于mapDispatchToProps已经传入了
```js
//方法注入
const mapDispatchToProps = (dispatch) => {
return {
addClick: () => {
dispatch({
type: `transaction/add`,
});
},
};
};
@connect(mapStateToProps, mapDispatchToProps)
class ProductList extends React.Component {
//...
constructor(props) {
super(props);
}
componentDidMount(){
console.log(this.props);
const {dispatch } = this.props;//获取不到dispatch方法
//事件
this.props.addClick();
}
}
如果写成如下
@connect(mapStateToProps)
class ProductList extends React.Component {
//...
constructor(props) {
super(props);
}
componentDidMount(){
console.log(this.props);
const {dispatch } = this.props;//可获取到dispatch方法
// 直接调用
dispatch({
type: `transaction/add`,
});
}
}