创建组件时调度动作

时间:2018-10-03 09:32:10

标签: reactjs redux react-redux

我有一个像这样的组件:

class FormItem extends React.PureComponent {

    constructor(props){
        super();
        props.dispatch(setFormCreated(props.formBuilder, props.formId)); 
    }

   render(){
       ...
   }
}

const mapStateToProps = state => {
    return {
        doValidation: state.formsReducer.validationRequested
    };
};

const mapDispatchToProps = dispatch => ({
    onValidationSucceed: formId =>  dispatch(setFormValidationSucceed(formId)),
    onValidationFailed: formId => dispatch(setFormValidationFailed(formId))
});

export default connect(mapStateToProps, mapDispatchToProps)(FormItem);

我想在创建组件时调度一个动作。第5行:

props.dispatch(setFormCreated(props.formBuilder, props.formId)); 

但是我得到了

  

TypeError:props.dispatch不是函数

2 个答案:

答案 0 :(得分:3)

在构造函数内部使用道具之前,您需要先传递超级道具:

super(props);

答案 1 :(得分:0)

const mapDispatchToProps = dispatch => ({
    onValidationSucceed: formId =>  dispatch(setFormValidationSucceed(formId)),
    onValidationFailed: formId => dispatch(setFormValidationFailed(formId))
    onFormCreated: (formBuilder, formId) => dispatch(setFormCreated(formBuilder, formId))
});

然后,您可以在您的组件中使用以下代码(我会将您的代码放在componentDidMount中)。这也假设您要传递formBuilderformId作为道具。

componentDidMount() {
  const { onFormCreated, formBuilder, formId } = this.props;
  onFormCreated(formBuilder, formId)
}