简体   繁体   English

redux通过bindActionCreators(一种反模式)进行预绑定?

[英]redux pre-binding through bindActionCreators, an anti-pattern?

Throughout my redux App, I frequently finding myself using the following pattern 在整个redux App中,我经常使用以下模式

// 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? 假设在redux中只有1个调度员对1个商店起作用?

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 由于这些组件将不再需要mapDispatchToProps来处理简单的情况,例如上面的示例

The connect function supports an "object shorthand" syntax for the second argument. connect函数支持第二个参数的“对象简写”语法。 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 : 无需创建一个接收dispatchmapDispatchToProps函数(并且可能在内部使用bindActionCreators ),您可以直接将一个充满动作创建者的对象直接传递给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. 充满动作创建者的对象将通过bindActionCreators自动运行,并调用this.props.addTodo("Buy Milk")将适当地分派动作创建者。

I discussed some of the advantages of this approach in my blog post Idiomatic Redux: Why use action creators? 我在博客文章Idiomatic Redux中讨论了这种方法的一些优点:为什么要使用动作创建者? .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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