Skip to content

Commit 48012ef

Browse files
iamtommccgaearon
authored andcommitted
Add warning for componentDidReceiveProps() (#11479)
* Add warning for componentDidReceiveProps() * Adjust message for componentDidReceiveProps() warning
1 parent acb268c commit 48012ef

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

packages/react-dom/src/__tests__/ReactCompositeComponent-test.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -533,6 +533,29 @@ describe('ReactCompositeComponent', () => {
533533
);
534534
});
535535

536+
it('should warn when componentDidReceiveProps method is defined', () => {
537+
spyOn(console, 'error');
538+
539+
class Component extends React.Component {
540+
componentDidReceiveProps = () => {};
541+
542+
render() {
543+
return <div />;
544+
}
545+
}
546+
547+
ReactTestUtils.renderIntoDocument(<Component />);
548+
549+
expectDev(console.error.calls.count()).toBe(1);
550+
expectDev(console.error.calls.argsFor(0)[0]).toBe(
551+
'Warning: Component has a method called ' +
552+
'componentDidReceiveProps(). But there is no such lifecycle method. ' +
553+
'If you meant to update the state in response to changing props, ' +
554+
'use componentWillReceiveProps(). If you meant to fetch data or ' +
555+
'run side-effects or mutations after React has updated the UI, use componentDidUpdate().',
556+
);
557+
});
558+
536559
it('should warn when defaultProps was defined as an instance property', () => {
537560
spyOn(console, 'error');
538561

packages/react-reconciler/src/ReactFiberClassComponent.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -281,6 +281,17 @@ export default function(
281281
'Did you mean componentWillUnmount()?',
282282
name,
283283
);
284+
const noComponentDidReceiveProps =
285+
typeof instance.componentDidReceiveProps !== 'function';
286+
warning(
287+
noComponentDidReceiveProps,
288+
'%s has a method called ' +
289+
'componentDidReceiveProps(). But there is no such lifecycle method. ' +
290+
'If you meant to update the state in response to changing props, ' +
291+
'use componentWillReceiveProps(). If you meant to fetch data or ' +
292+
'run side-effects or mutations after React has updated the UI, use componentDidUpdate().',
293+
name,
294+
);
284295
const noComponentWillRecieveProps =
285296
typeof instance.componentWillRecieveProps !== 'function';
286297
warning(

0 commit comments

Comments
 (0)