diff --git a/src/core/ReactCompositeComponent.js b/src/core/ReactCompositeComponent.js index 2cdc1a89f99..82d99539ecc 100644 --- a/src/core/ReactCompositeComponent.js +++ b/src/core/ReactCompositeComponent.js @@ -686,6 +686,12 @@ var ReactCompositeComponentMixin = { } this.state = this.getInitialState ? this.getInitialState() : null; + invariant( + typeof this.state === 'object' && !Array.isArray(this.state), + '%s.getInitialState(): must return an object or null', + this.constructor.displayName || 'ReactCompositeComponent' + ); + this._pendingState = null; this._pendingForceUpdate = false; diff --git a/src/core/__tests__/ReactCompositeComponent-test.js b/src/core/__tests__/ReactCompositeComponent-test.js index fa1b866e002..10f668eecc4 100644 --- a/src/core/__tests__/ReactCompositeComponent-test.js +++ b/src/core/__tests__/ReactCompositeComponent-test.js @@ -458,6 +458,54 @@ describe('ReactCompositeComponent', function() { ); }); + it('should work with a null getInitialState() return value', function() { + var Component = React.createClass({ + getInitialState: function() { + return null; + }, + render: function() { + return ; + } + }); + expect(() => ).not.toThrow(); + }); + + it('should work with object getInitialState() return values', function() { + var Component = React.createClass({ + getInitialState: function() { + return { + occupation: 'clown' + }; + }, + render: function() { + return ; + } + }); + var instance = ; + ReactTestUtils.renderIntoDocument(instance); + expect(instance.state.occupation).toEqual('clown'); + }); + + it('should throw with non-object getInitialState() return values', function() { + [['an array'], 'a string', 1234].forEach(function(state) { + var Component = React.createClass({ + getInitialState: function() { + return state; + }, + render: function() { + return ; + } + }); + var instance = ; + expect(function() { + ReactTestUtils.renderIntoDocument(instance); + }).toThrow( + 'Invariant Violation: Component.getInitialState(): ' + + 'must return an object or null' + ); + }); + }); + it('should detect valid CompositeComponent classes', function() { var Component = React.createClass({ render: function() {