Action binding options in mapDispatchToProps

I have a submit button that will send an action. The action payload is the data that will be sent to the API. I am currently using bindActionCreatorsin mapDispatchToProps:

const mapDispatchToProps = (dispatch) => ({
    actions:  bindActionCreators(FormActions, dispatch)
});

then in my component I bind onClickto the submit action:

<input type="submit" onClick={() => this.props.actions.submit(this.props.postData)} />

I do not like that I have to provide this component with message data in mapStateToProps. I would prefer to simply indicate to the component an action that already has data associated with the submit function, so the usage would look like this:

<input type="submit" onClick={this.props.submit} />

Is it possible? I do not have access to state inmapDispatchToProps

+4
source share
1 answer

mergeProps connect react-redux, , . - :

const mapStateToProps = state => ({ postData: ... });

const mapDispatchToProps = (dispatch) => ({
  actions:  bindActionCreators(FormActions, dispatch)
});

const mergeProps = (stateProps, dispatchProps) => ({
  submit: () => dispatchProps.actions.submit(stateProps.postData),
});

const ConnectedComponent = connect(mapStateToProps, mapDispatchToProps, mergeProps)(Component);

, actions postData, submit.

+3

Source: https://habr.com/ru/post/1674329/


All Articles