Skip to content

Commit

Permalink
getDerivedStateFromProps now creates new versions instead of mutati…
Browse files Browse the repository at this point in the history
…ng state
  • Loading branch information
mitranim committed Jul 29, 2018
1 parent ea932dd commit 576c891
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 5 deletions.
4 changes: 2 additions & 2 deletions src/vdom/component.js
Expand Up @@ -84,8 +84,8 @@ export function renderComponent(component, renderMode, mountAll, isChild) {
rendered, inst, cbase;

if (component.constructor.getDerivedStateFromProps) {
previousState = extend({}, previousState);
component.state = extend(state, component.constructor.getDerivedStateFromProps(props, state));
state = extend(extend({}, state), component.constructor.getDerivedStateFromProps(props, state));
component.state = state;
}

// if updating
Expand Down
29 changes: 26 additions & 3 deletions test/browser/lifecycle.js
Expand Up @@ -505,6 +505,31 @@ describe('Lifecycle methods', () => {
value: 3
});
});

it('should NOT mutate state, only create new versions', () => {
const stateConstant = {};
let componentState;

class Stateful extends Component {
static getDerivedStateFromProps() {
return {key: 'value'};
}

constructor() {
super(...arguments);
this.state = stateConstant;
}

componentDidMount() {
componentState = this.state;
}
}

render(<Stateful />, scratch);

expect(componentState).to.deep.equal({key: 'value'});
expect(stateConstant).to.deep.equal({});
});
});

describe("#getSnapshotBeforeUpdate", () => {
Expand Down Expand Up @@ -1326,13 +1351,11 @@ describe('Lifecycle methods', () => {


describe('#setState', () => {
it('should not mutate state, only create new versions', () => {
it('should NOT mutate state, only create new versions', () => {
const stateConstant = {};
let didMount = false;
let componentState;

expect(stateConstant).to.deep.equal({});

class Stateful extends Component {
constructor() {
super(...arguments);
Expand Down

0 comments on commit 576c891

Please sign in to comment.