From d268e4051a05b25ce6973a4ab6874813c659a760 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=9A=93=E9=BB=98?= Date: Tue, 6 Feb 2018 20:28:53 +0800 Subject: [PATCH] fix: children.map when child return null --- src/index.js | 18 ++++++++++++++++-- test/component.js | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/src/index.js b/src/index.js index ba0fe64..fe8c728 100644 --- a/src/index.js +++ b/src/index.js @@ -185,12 +185,26 @@ function unmountComponentAtNode(container) { const ARR = []; // This API is completely unnecessary for Preact, so it's basically passthrough. + let Children = { map(children, fn, ctx) { if (children == null) return null; children = Children.toArray(children); if (ctx && ctx!==children) fn = fn.bind(ctx); - return children.map(fn); + const newChildren = []; + + children.forEach((old, index) => { + if (old === void 0 || old === false || old === true) { + old = null; + } + const newChild = fn(old, index); + if (newChild == null) { // when the return value is null, ignore + return; + } + newChildren.push(newChild); + }); + + return newChildren; }, forEach(children, fn, ctx) { if (children == null) return null; @@ -592,7 +606,7 @@ PureComponent.prototype.shouldComponentUpdate = function(props, state) { }; function unstable_batchedUpdates(callback) { - callback(); + callback(); } export { diff --git a/test/component.js b/test/component.js index 33faeda..f1869f3 100644 --- a/test/component.js +++ b/test/component.js @@ -543,4 +543,36 @@ describe('components', () => { expect(spy).not.to.have.been.called; }); }); + + describe('ReactChildren', () => { + it("should ignore when child return null", () => { + let zero =
; + let one = null; + let two =
; + let three = null; + let four =
; + + let mapped = [ +
, // Key should be joined to obj key + null, // Key should be added even if we don't supply it! +
, // Key should be added even if not supplied! + , // Map from null to something. +
+ ]; + let instance = ( +
+ {zero} + {one} + {two} + {three} + {four} +
+ ); + const mappedChildren = React.Children.map(instance.props.children, (kid, index) => mapped[index]); + expect(mappedChildren[0]).to.equal(
); + expect(mappedChildren[1]).to.equal(
); + expect(mappedChildren[2]).to.equal(); + expect(mappedChildren[3]).to.equal(
); + }); + }); });