Skip to content

Commit d22211e

Browse files
Fix exception when invoking setState in cWM
1 parent 29482d4 commit d22211e

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

src/index.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,11 @@ function renderToString(vnode, context, opts, inner, isSvgMode, selectValue) {
104104
c._dirty = c.__d = true;
105105
c.props = props;
106106
if (c.state==null) c.state = {};
107+
108+
if (c._nextState==null && c.__s==null) {
109+
c._nextState = c.__s = c.state;
110+
}
111+
107112
c.context = cctx;
108113
if (nodeName.getDerivedStateFromProps) c.state = assign(assign({}, c.state), nodeName.getDerivedStateFromProps(c.props, c.state));
109114
else if (c.componentWillMount) c.componentWillMount();

test/render.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -354,6 +354,28 @@ describe('render', () => {
354354
.and.to.have.been.calledBefore(Test.prototype.render);
355355
});
356356

357+
it('should be able to call setState in componentWillMount', () => {
358+
class Test extends Component {
359+
constructor(props) {
360+
super(props);
361+
this.state = { updated: false };
362+
}
363+
componentWillMount() {
364+
this.setState({ updated: true });
365+
}
366+
367+
render() {
368+
return (
369+
<p>
370+
{this.state.updated.toString()}
371+
</p>
372+
);
373+
}
374+
}
375+
376+
expect(render(<Test />)).to.equal('<p>false</p>');
377+
});
378+
357379
it('should invoke getDerivedStateFromProps rather than componentWillMount', () => {
358380
class Test extends Component {
359381
static getDerivedStateFromProps() {}

0 commit comments

Comments
 (0)