浏览代码

composeReducers

Herbert Vojčík 7 年之前
父节点
当前提交
096e70f088
共有 3 个文件被更改,包括 33 次插入1 次删除
  1. 17 0
      README.md
  2. 13 1
      lib/node.js
  3. 3 0
      src/node.js

+ 17 - 0
README.md

@@ -42,3 +42,20 @@ will be fetched and passed to a sub-reducer:
 ```
 
 This technique is mentioned in Redux docs, in "Beyond combineReducers" page.
+
+## `composeReducers(reducer1, reducer2, ...)`
+
+Creates a wrapper reducer that calls passed reducers
+one after another, passing intermediate states.
+and returning the result of the last one.
+
+Useful to "concatenate" a few `subReducer`s. like:
+
+```js
+	combineReducers(
+	    subReducer("files.persons", personReducer, "assets.swag"),
+	    subReducer("files.clients", clientReducer, "news"),
+	    subReducer("assets", assetReducer),
+	    baseReducer
+	)
+```

+ 13 - 1
lib/node.js

@@ -3,7 +3,7 @@
 Object.defineProperty(exports, "__esModule", {
     value: true
 });
-exports.subReducer = undefined;
+exports.composeReducers = exports.subReducer = undefined;
 
 var _cowValueModel2 = require("./cow-value-model");
 
@@ -30,4 +30,16 @@ var subReducer = exports.subReducer = function subReducer(key, reducer) {
         }
         return setValue(state, newSubState);
     };
+};
+
+var composeReducers = exports.composeReducers = function composeReducers() {
+    for (var _len2 = arguments.length, reducers = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+        reducers[_key2] = arguments[_key2];
+    }
+
+    return function (state, action) {
+        return reducers.reduce(function (x, r) {
+            return r(x, action);
+        }, state);
+    };
 };

+ 3 - 0
src/node.js

@@ -12,3 +12,6 @@ export const subReducer = (key, reducer, ...otherKeys) => {
         return setValue(state, newSubState);
     };
 };
+
+export const composeReducers = (...reducers) => (state, action) =>
+    reducers.reduce((x, r) => r(x, action), state);