Skip to content

Commit 22743d7

Browse files
Merge pull request #155 from preactjs/bugfix/get-derived-state-from-props
Keep state changes during getDerivedStateFromProps
2 parents 58f0cca + 9cf6616 commit 22743d7

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
@@ -336,19 +336,23 @@ describe('render', () => {
336336

337337
it('should invoke getDerivedStateFromProps', () => {
338338
class Test extends Component {
339-
static getDerivedStateFromProps() {}
340-
render(props) {
341-
return <div {...props} />;
339+
static getDerivedStateFromProps() {
340+
return { foo: 'bar' };
341+
}
342+
render(props, state) {
343+
return <div {...props} {...state} />;
342344
}
343345
}
344346
spy(Test.prototype.constructor, 'getDerivedStateFromProps');
345347
spy(Test.prototype, 'render');
346348

347-
render(<Test />);
349+
const result = render(<Test />);
348350

349351
expect(Test.prototype.constructor.getDerivedStateFromProps)
350352
.to.have.been.calledOnce
351353
.and.to.have.been.calledBefore(Test.prototype.render);
354+
355+
expect(result).to.equal('<div foo="bar"></div>');
352356
});
353357

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

0 commit comments

Comments
 (0)