From 7d91277a5025cd08210d2362ade4ca92676a5fa2 Mon Sep 17 00:00:00 2001 From: Daniel Schonfeld Date: Sat, 10 May 2014 23:56:42 -0400 Subject: [PATCH] warn when shouldComponentUpdate() returns undefined --- src/core/ReactCompositeComponent.js | 19 +++++++++-- .../__tests__/ReactCompositeComponent-test.js | 32 +++++++++++++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/src/core/ReactCompositeComponent.js b/src/core/ReactCompositeComponent.js index 668074bdae..1f86ab7c32 100644 --- a/src/core/ReactCompositeComponent.js +++ b/src/core/ReactCompositeComponent.js @@ -1000,9 +1000,22 @@ var ReactCompositeComponentMixin = { this._pendingState = null; try { - if (this._pendingForceUpdate || - !this.shouldComponentUpdate || - this.shouldComponentUpdate(nextProps, nextState, nextContext)) { + var shouldUpdate = + this._pendingForceUpdate || + !this.shouldComponentUpdate || + this.shouldComponentUpdate(nextProps, nextState, nextContext); + + if (__DEV__) { + if (typeof shouldUpdate === "undefined") { + console.warn( + (this.constructor.displayName || 'ReactCompositeComponent') + + '.shouldComponentUpdate(): Returned undefined instead of a ' + + 'boolean value. Make sure to return true or false.' + ); + } + } + + if (shouldUpdate) { this._pendingForceUpdate = false; // Will set `this.props`, `this.state` and `this.context`. this._performComponentUpdate( diff --git a/src/core/__tests__/ReactCompositeComponent-test.js b/src/core/__tests__/ReactCompositeComponent-test.js index e3a9d2af52..609392c2a2 100644 --- a/src/core/__tests__/ReactCompositeComponent-test.js +++ b/src/core/__tests__/ReactCompositeComponent-test.js @@ -871,6 +871,38 @@ describe('ReactCompositeComponent', function() { expect(React.isValidClass(TrickFnComponent)).toBe(false); }); + it('should warn when shouldComponentUpdate() returns undefined', function() { + var warn = console.warn; + console.warn = mocks.getMockFunction(); + + try { + var Component = React.createClass({ + getInitialState: function () { + return {bogus: false}; + }, + + shouldComponentUpdate: function() { + return undefined; + }, + + render: function() { + return
; + } + }); + + var instance = ReactTestUtils.renderIntoDocument(); + instance.setState({bogus: true}); + + expect(console.warn.mock.calls.length).toBe(1); + expect(console.warn.mock.calls[0][0]).toBe( + 'Component.shouldComponentUpdate(): Returned undefined instead of a ' + + 'boolean value. Make sure to return true or false.' + ); + } finally { + console.warn = warn; + } + }); + it('should warn when mispelling shouldComponentUpdate', function() { var warn = console.warn; console.warn = mocks.getMockFunction();