简体   繁体   中英

redux pre-binding through bindActionCreators, an anti-pattern?

Throughout my redux App, I frequently finding myself using the following pattern

// declare an action creator in a centralized / state management related location in the App (i.e. not the components/containers)
const myActionCreator1 = () => (dispatch) => { ... }
const myActionCreator2 = createAction(ACTION_2)
// then later in a mapDispatchToProps of a Container component
function mapDispatchToProps(dispatch) {
  bindActionCreators({myActionCreator1, myActionCreator2}, dispatch);
}

Is these cases, is it an anti-pattern to pre-bind the action creators? given that there is only 1 dispatcher in redux working against 1 store?

ie

// actionCreators.ts
export const myActionCreators = {
  myActionCreator: bindActionCreators(..., dispatch)
}

If this is pattern has no downside that would be good news for conciseness ....

Clarification

the conciseness benefit will only be apparent when multiple components re-use the same action creator. As these components will no longer require a mapDispatchToProps for straight-forward cases like the examples above

The connect function supports an "object shorthand" syntax for the second argument. Instead of creating a mapDispatchToProps function that receives dispatch (and probably uses bindActionCreators inside), you can just pass an object full of action creators directly to connect :

const actionCreators = {
    addTodo,
    toggleTodo
};

export default connect(null, actionCreators)(MyComponent);

That object full of action creators will be automatically run through bindActionCreators , and calling this.props.addTodo("Buy Milk") will dispatch the action creator appropriately.

I discussed some of the advantages of this approach in my blog post Idiomatic Redux: Why use action creators? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM