Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/core/ReactCompositeComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -686,6 +686,12 @@ var ReactCompositeComponentMixin = {
}

this.state = this.getInitialState ? this.getInitialState() : null;
invariant(
typeof this.state === 'object' && !Array.isArray(this.state),
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

undefined should also be valid. Otherwise a function like this would fatal:

getInitialState: function() {
  if (something) {
    return {some: 'abc'};
  }
}

'%s.getInitialState(): must return an object or null',
this.constructor.displayName || 'ReactCompositeComponent'
);

this._pendingState = null;
this._pendingForceUpdate = false;

Expand Down
48 changes: 48 additions & 0 deletions src/core/__tests__/ReactCompositeComponent-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 <span />;
}
});
expect(() => <Component />).not.toThrow();
});

it('should work with object getInitialState() return values', function() {
var Component = React.createClass({
getInitialState: function() {
return {
occupation: 'clown'
};
},
render: function() {
return <span />;
}
});
var instance = <Component />;
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 <span />;
}
});
var instance = <Component />;
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() {
Expand Down