Add invariant to check getInitialState return value. Fixes #397
cpojer committed
Dec 27, 2013 at 14:17 UTC
77697f26e32e1625397e6cdcb0defe0a746b7230
2 files changed
+54
src/core/ReactCompositeComponent.js
+6
@@ -686,6 +686,12 @@ var ReactCompositeComponentMixin = {
686
}
687
688
this.state = this.getInitialState ? this.getInitialState() : null;
689
+ invariant(
690
+ typeof this.state === 'object' && !Array.isArray(this.state),
691
+ '%s.getInitialState(): must return an object or null',
692
+ this.constructor.displayName || 'ReactCompositeComponent'
693
+ );
694
+
695
this._pendingState = null;
696
this._pendingForceUpdate = false;
697
src/core/__tests__/ReactCompositeComponent-test.js
+48
@@ -458,6 +458,54 @@ describe('ReactCompositeComponent', function() {
458
);
459
});
460
461
+ it('should work with a null getInitialState() return value', function() {
462
+ var Component = React.createClass({
463
+ getInitialState: function() {
464
+ return null;
465
+ },
466
+ render: function() {
467
+ return <span />;
468
+ }
469
+ });
470
+ expect(() => <Component />).not.toThrow();
471
+ });
472
+
473
+ it('should work with object getInitialState() return values', function() {
474
+ var Component = React.createClass({
475
+ getInitialState: function() {
476
+ return {
477
+ occupation: 'clown'
478
+ };
479
+ },
480
+ render: function() {
481
+ return <span />;
482
+ }
483
+ });
484
+ var instance = <Component />;
485
+ ReactTestUtils.renderIntoDocument(instance);
486
+ expect(instance.state.occupation).toEqual('clown');
487
+ });
488
+
489
+ it('should throw with non-object getInitialState() return values', function() {
490
+ [['an array'], 'a string', 1234].forEach(function(state) {
491
+ var Component = React.createClass({
492
+ getInitialState: function() {
493
+ return state;
494
+ },
495
+ render: function() {
496
+ return <span />;
497
+ }
498
+ });
499
+ var instance = <Component />;
500
+ expect(function() {
501
+ ReactTestUtils.renderIntoDocument(instance);
502
+ }).toThrow(
503
+ 'Invariant Violation: Component.getInitialState(): ' +
504
+ 'must return an object or null'
505
+ );
506
+ });
507
+ });
508
+
509
it('should detect valid CompositeComponent classes', function() {
510
var Component = React.createClass({
511
render: function() {