Skip to content

Commit 9cf6616

Browse files
committed
Keep state changes during getDerivedStateFromProps
Signed-off-by: Sven Tschui <[email protected]>
1 parent 09d7675 commit 9cf6616

File tree

2 files changed

+17
-11
lines changed

2 files changed

+17
-11
lines changed

src/index.js

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -122,13 +122,15 @@ function renderToString(vnode, context, opts, inner, isSvgMode, selectValue) {
122122

123123
c.context = cctx;
124124
if (nodeName.getDerivedStateFromProps) c.state = assign(assign({}, c.state), nodeName.getDerivedStateFromProps(c.props, c.state));
125-
else if (c.componentWillMount) c.componentWillMount();
126-
127-
// If the user called setState in cWM we need to flush pending,
128-
// state updates. This is the same behaviour in React.
129-
c.state = c._nextState !== c.state
130-
? c._nextState : c.__s!==c.state
131-
? c.__s : c.state;
125+
else if (c.componentWillMount) {
126+
c.componentWillMount();
127+
128+
// If the user called setState in cWM we need to flush pending,
129+
// state updates. This is the same behaviour in React.
130+
c.state = c._nextState !== c.state
131+
? c._nextState : c.__s!==c.state
132+
? c.__s : c.state;
133+
}
132134

133135
rendered = c.render(c.props, c.state, c.context);
134136
}

test/render.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -329,19 +329,23 @@ describe('render', () => {
329329

330330
it('should invoke getDerivedStateFromProps', () => {
331331
class Test extends Component {
332-
static getDerivedStateFromProps() {}
333-
render(props) {
334-
return <div {...props} />;
332+
static getDerivedStateFromProps() {
333+
return { foo: 'bar' };
334+
}
335+
render(props, state) {
336+
return <div {...props} {...state} />;
335337
}
336338
}
337339
spy(Test.prototype.constructor, 'getDerivedStateFromProps');
338340
spy(Test.prototype, 'render');
339341

340-
render(<Test />);
342+
const result = render(<Test />);
341343

342344
expect(Test.prototype.constructor.getDerivedStateFromProps)
343345
.to.have.been.calledOnce
344346
.and.to.have.been.calledBefore(Test.prototype.render);
347+
348+
expect(result).to.equal('<div foo="bar"></div>');
345349
});
346350

347351
it('should invoke componentWillMount', () => {

0 commit comments

Comments
 (0)