Redux: 功能请求:允许 bindActionCreators 接受数组

创建于 2016-06-10  ·  3评论  ·  资料来源: reduxjs/redux

目前, bindActionCreators接受单个函数或函数对象。 如果它也接受一个数组,这将很有用,以帮助这个代码模式:

import * as ac from './actionCreators';

// later in file...
const [doThis, doSomethingElse, doAnotherThing] = bindActionCreators(
  [ac.doThis, ac.doSomethingElse, ac.doAnotherThing
], dispatch);
// ...

我喜欢明确指定我的创建者名称,因为任何错误都会被eslint-plugin-import/namespace立即捕获为错误。

我相信这是必要的改变:

diff --git a/src/bindActionCreators.js b/src/bindActionCreators.js
index e70e270..6050c32 100644
--- a/src/bindActionCreators.js
+++ b/src/bindActionCreators.js
@@ -28,6 +28,10 @@ export default function bindActionCreators(actionCreators, dispatch) {
     return bindActionCreator(actionCreators, dispatch)
   }

+  if (Array.isArray(actionCreators)) {
+    return actionCreators.map(ac => bindActionCreator(ac, dispatch));
+  }
+
   if (typeof actionCreators !== 'object' || actionCreators === null) {
     throw new Error(
       `bindActionCreators expected an object or a function, instead received ${actionCreators === null ? 'null' : typeof actionCreators}. ` +

最有用的评论

我认为让bindActionCreator更多的多态性太多了,创建一个包装函数来为你做这件事怎么样?

function mapBindActionCreators(actions, dispatch) {
  return actions.map(action => bindActionCreator(action, dispatch)
}

所有3条评论

我认为让bindActionCreator更多的多态性太多了,创建一个包装函数来为你做这件事怎么样?

function mapBindActionCreators(actions, dispatch) {
  return actions.map(action => bindActionCreator(action, dispatch)
}

如果你有一个数组,你可以将数组reduce()放入一个对象并将其传递给bindActionCreator

是的,我想我们想避免在这里支持所有可能的排列。

此页面是否有帮助?
0 / 5 - 0 等级

相关问题

captbaritone picture captbaritone  ·  3评论

amorphius picture amorphius  ·  3评论

rui-ktei picture rui-ktei  ·  3评论

caojinli picture caojinli  ·  3评论

timdorr picture timdorr  ·  3评论