Skip to content

Commit

Permalink
Support defaultProps resolution
Browse files Browse the repository at this point in the history
  • Loading branch information
sebmarkbage committed Nov 5, 2018
1 parent bd99c87 commit 7006c4b
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
18 changes: 18 additions & 0 deletions packages/react-debug-tools/src/ReactDebugHooks.js
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,21 @@ function inspectHooksOfForwardRef<Props, Ref>(
return buildTree(rootStack, readHookLog);
}

function resolveDefaultProps(Component, baseProps) {
if (Component && Component.defaultProps) {
// Resolve default props. Taken from ReactElement
const props = Object.assign({}, baseProps);
const defaultProps = Component.defaultProps;
for (let propName in defaultProps) {
if (props[propName] === undefined) {
props[propName] = defaultProps[propName];
}
}
return props;
}
return baseProps;
}

export function inspectHooksOfFiber(fiber: Fiber) {
if (
fiber.tag !== FunctionComponent &&
Expand All @@ -495,6 +510,9 @@ export function inspectHooksOfFiber(fiber: Fiber) {
getPrimitiveStackCache();
let type = fiber.type;
let props = fiber.memoizedProps;
if (type !== fiber.elementType) {
props = resolveDefaultProps(type, props);
}
// Set up the current hook so that we can step through and read the
// current state from them.
currentHook = (fiber.memoizedState: Hook);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,4 +214,34 @@ describe('ReactHooksInspectionIntergration', () => {
},
]);
});

it('should support defaultProps and lazy', async () => {
let Suspense = React.Suspense;

function Foo(props) {
let [value] = React.useState(props.defaultValue.substr(0, 3));
return <div>{value}</div>;
}
Foo.defaultProps = {
defaultValue: 'default',
};

async function fakeImport(result) {
return {default: result};
}

let LazyFoo = React.lazy(() => fakeImport(Foo));

let renderer = ReactTestRenderer.create(
<Suspense fallback="Loading...">
<LazyFoo />
</Suspense>,
);

await LazyFoo;

let childFiber = renderer.root._currentFiber();
let tree = ReactDebugTools.inspectHooksOfFiber(childFiber);
expect(tree).toEqual([{name: 'State', value: 'def', subHooks: []}]);
});
});

0 comments on commit 7006c4b

Please sign in to comment.