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 評価