From 48012ef839bc13e35188b68d2db145869a6a05f5 Mon Sep 17 00:00:00 2001 From: Tom Date: Wed, 8 Nov 2017 00:00:31 +1000 Subject: [PATCH] Add warning for componentDidReceiveProps() (#11479) * Add warning for componentDidReceiveProps() * Adjust message for componentDidReceiveProps() warning --- .../__tests__/ReactCompositeComponent-test.js | 23 +++++++++++++++++++ .../src/ReactFiberClassComponent.js | 11 +++++++++ 2 files changed, 34 insertions(+) diff --git a/packages/react-dom/src/__tests__/ReactCompositeComponent-test.js b/packages/react-dom/src/__tests__/ReactCompositeComponent-test.js index af7688573b..51730d7ff8 100644 --- a/packages/react-dom/src/__tests__/ReactCompositeComponent-test.js +++ b/packages/react-dom/src/__tests__/ReactCompositeComponent-test.js @@ -533,6 +533,29 @@ describe('ReactCompositeComponent', () => { ); }); + it('should warn when componentDidReceiveProps method is defined', () => { + spyOn(console, 'error'); + + class Component extends React.Component { + componentDidReceiveProps = () => {}; + + render() { + return
; + } + } + + ReactTestUtils.renderIntoDocument(); + + expectDev(console.error.calls.count()).toBe(1); + expectDev(console.error.calls.argsFor(0)[0]).toBe( + 'Warning: Component has a method called ' + + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + + 'If you meant to update the state in response to changing props, ' + + 'use componentWillReceiveProps(). If you meant to fetch data or ' + + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', + ); + }); + it('should warn when defaultProps was defined as an instance property', () => { spyOn(console, 'error'); diff --git a/packages/react-reconciler/src/ReactFiberClassComponent.js b/packages/react-reconciler/src/ReactFiberClassComponent.js index e93a2310b0..96449a77ff 100644 --- a/packages/react-reconciler/src/ReactFiberClassComponent.js +++ b/packages/react-reconciler/src/ReactFiberClassComponent.js @@ -281,6 +281,17 @@ export default function( 'Did you mean componentWillUnmount()?', name, ); + const noComponentDidReceiveProps = + typeof instance.componentDidReceiveProps !== 'function'; + warning( + noComponentDidReceiveProps, + '%s has a method called ' + + 'componentDidReceiveProps(). But there is no such lifecycle method. ' + + 'If you meant to update the state in response to changing props, ' + + 'use componentWillReceiveProps(). If you meant to fetch data or ' + + 'run side-effects or mutations after React has updated the UI, use componentDidUpdate().', + name, + ); const noComponentWillRecieveProps = typeof instance.componentWillRecieveProps !== 'function'; warning(