Test top level fragment inside lazy semantics (#28852)

This wasn't clearly articulated and tested why the code structure is
like this but I think the logic is correct - or at least consistent with
the weird semantics.

We place this top-level fragment check inside the recursion so that you
can resolve how many every Lazy or Usable wrappers you want and it still
preserves the same semantics if they weren't there (which they might not
be as a matter of a race condition).

However, we don't actually recurse with the top-level fragment
unwrapping itself because nesting a bunch of keyless fragments isn't the
same as a single fragment/element.
This commit is contained in:
Sebastian Markbåge
2024-04-17 12:37:51 -04:00
committed by GitHub
parent d45e4c44e3
commit 533df973db
2 changed files with 52 additions and 2 deletions
+5 -2
View File
@@ -1460,7 +1460,9 @@ function createChildReconciler(
lanes: Lanes,
debugInfo: ReactDebugInfo | null,
): Fiber | null {
// This function is not recursive.
// This function is only recursive for Usables/Lazy and not nested arrays.
// That's so that using a Lazy wrapper is unobservable to the Fragment
// convention.
// If the top level item is an array, we treat it as a set of children,
// not as a fragment. Nested arrays on the other hand will be treated as
// fragment nodes. Recursion happens at the normal flow.
@@ -1468,7 +1470,8 @@ function createChildReconciler(
// Handle top level unkeyed fragments as if they were arrays.
// This leads to an ambiguity between <>{[...]}</> and <>...</>.
// We treat the ambiguous cases above the same.
// TODO: Let's use recursion like we do for Usable nodes?
// We don't use recursion here because a fragment inside a fragment
// is no longer considered "top level" for these purposes.
const isUnkeyedTopLevelFragment =
typeof newChild === 'object' &&
newChild !== null &&
@@ -965,4 +965,51 @@ describe('ReactFragment', () => {
</>,
);
});
it('should preserve state of children when adding a fragment wrapped in Lazy', async function () {
const ops = [];
class Stateful extends React.Component {
componentDidUpdate() {
ops.push('Update Stateful');
}
render() {
return <div>Hello</div>;
}
}
const lazyChild = React.lazy(async () => ({
default: (
<>
<Stateful key="a" />
<div key="b">World</div>
</>
),
}));
function Foo({condition}) {
return condition ? <Stateful key="a" /> : lazyChild;
}
ReactNoop.render(<Foo condition={true} />);
await waitForAll([]);
ReactNoop.render(<Foo condition={false} />);
await waitForAll([]);
expect(ops).toEqual(['Update Stateful']);
expect(ReactNoop).toMatchRenderedOutput(
<>
<div>Hello</div>
<div>World</div>
</>,
);
ReactNoop.render(<Foo condition={true} />);
await waitForAll([]);
expect(ops).toEqual(['Update Stateful', 'Update Stateful']);
expect(ReactNoop).toMatchRenderedOutput(<div>Hello</div>);
});
});