Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed a batched-state update bug with getDerivedStateFromProps #12408

Merged
merged 4 commits into from
Mar 21, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
45 changes: 45 additions & 0 deletions packages/react-dom/src/__tests__/ReactComponentLifeCycle-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -830,4 +830,49 @@ describe('ReactComponentLifeCycle', () => {
'UNSAFE_componentWillUpdate',
]);
});

it('should not override state with stale values if prevState is spread within getDerivedStateFromProps', () => {
let childInstance;

class Child extends React.Component {
state = {local: 0};
static getDerivedStateFromProps(nextProps, prevState) {
return {...prevState, remote: nextProps.remote};
}
updateState = () => {
this.setState(state => ({local: state.local + 1}));
this.props.onChange(this.state.remote + 1);
};
render() {
childInstance = this;
return (
<div onClick={this.updateState}>{`remote:${
this.state.remote
}, local:${this.state.local}`}</div>
);
}
}

class Parent extends React.Component {
state = {value: 0};
handleChange = value => {
this.setState({value});
};
render() {
return <Child remote={this.state.value} onChange={this.handleChange} />;
}
}

const instance = ReactTestUtils.renderIntoDocument(<Parent />);
const element = ReactDOM.findDOMNode(instance);
Copy link
Collaborator

Choose a reason for hiding this comment

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

Nit: let's not use findDOMNode. Maybe a ref instead? I know it's just a test, but we should still try to avoid using legacy APIs :D

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I confess, I often copy paste an existing test when writing a new one to save a few seconds.

expect(element.textContent).toBe('remote:0, local:0');

// Trigger setState() calls
childInstance.updateState();
expect(element.textContent).toBe('remote:1, local:1');

// Trigger batched setState() calls
ReactTestUtils.Simulate.click(element);
expect(element.textContent).toBe('remote:2, local:2');
});
});
1 change: 1 addition & 0 deletions packages/react-reconciler/src/ReactFiberBeginWork.js
Original file line number Diff line number Diff line change
Expand Up @@ -612,6 +612,7 @@ export default function<T, P, I, TI, HI, PI, C, CC, CX, PL>(
workInProgress,
value,
props,
workInProgress.memoizedState,
);

if (partialState !== null && partialState !== undefined) {
Expand Down
63 changes: 33 additions & 30 deletions packages/react-reconciler/src/ReactFiberClassComponent.js
Original file line number Diff line number Diff line change
Expand Up @@ -448,6 +448,7 @@ export default function(
workInProgress,
instance,
props,
state,
);

if (partialState !== null && partialState !== undefined) {
Expand Down Expand Up @@ -534,7 +535,8 @@ export default function(
function callGetDerivedStateFromProps(
workInProgress: Fiber,
instance: any,
props: any,
nextProps: any,
prevState: any,
) {
const {type} = workInProgress;

Expand Down Expand Up @@ -567,17 +569,13 @@ export default function(
workInProgress.mode & StrictMode)
) {
// Invoke method an extra time to help detect side-effects.
type.getDerivedStateFromProps.call(
null,
props,
workInProgress.memoizedState,
);
type.getDerivedStateFromProps.call(null, nextProps, prevState);
}

const partialState = type.getDerivedStateFromProps.call(
null,
props,
workInProgress.memoizedState,
nextProps,
prevState,
);

if (__DEV__) {
Expand Down Expand Up @@ -698,19 +696,21 @@ export default function(
}
}

// Compute the next state using the memoized state and the update queue.
const oldState = workInProgress.memoizedState;
// TODO: Previous state can be null.
let newState;

let derivedStateFromProps;
if (oldProps !== newProps) {
derivedStateFromProps = callGetDerivedStateFromProps(
workInProgress,
instance,
newProps,
oldState,
);
}

// Compute the next state using the memoized state and the update queue.
const oldState = workInProgress.memoizedState;
// TODO: Previous state can be null.
let newState;
let derivedStateFromCatch;
if (workInProgress.updateQueue !== null) {
newState = processUpdateQueue(
Expand Down Expand Up @@ -867,19 +867,11 @@ export default function(
}
}

let derivedStateFromProps;
Copy link
Collaborator

Choose a reason for hiding this comment

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

Why did you change the order of getDerivedStateFromCatch and getDerivedStateFromProps? The new order seems correct, just curious what led you to make the change in this diff.

It looks like the order in the "resume mount" path is different now, though. Should be consistent regardless.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Why did you change the order of getDerivedStateFromCatch and getDerivedStateFromProps?

This was incidental. I changed the order of processUpdateQueue and getDerivedStateFromProps. I did that because it seemed easier to get the correct partial state value that way than trying to mess with the update queue and it's memoized vs base state.

It looks like the order in the "resume mount" path is different now, though. Should be consistent regardless.

Fair 👍

Copy link
Collaborator

@acdlite acdlite Mar 21, 2018

Choose a reason for hiding this comment

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

One more thing: could you add a test so the order doesn't incidentally change in the future?

if (oldProps !== newProps) {
derivedStateFromProps = callGetDerivedStateFromProps(
workInProgress,
instance,
newProps,
);
}

// Compute the next state using the memoized state and the update queue.
const oldState = workInProgress.memoizedState;
// TODO: Previous state can be null.
let newState;
let newState = oldState;

let derivedStateFromCatch;
if (workInProgress.updateQueue !== null) {
newState = processUpdateQueue(
Expand Down Expand Up @@ -908,27 +900,38 @@ export default function(
capturedValues,
);
}
} else {
newState = oldState;
}

if (derivedStateFromProps !== null && derivedStateFromProps !== undefined) {
if (derivedStateFromCatch !== null && derivedStateFromCatch !== undefined) {
// Render-phase updates (like this) should not be added to the update queue,
// So that multiple render passes do not enqueue multiple updates.
// Instead, just synchronously merge the returned state into the instance.
newState =
newState === null || newState === undefined
? derivedStateFromProps
: Object.assign({}, newState, derivedStateFromProps);
? derivedStateFromCatch
: Object.assign({}, newState, derivedStateFromCatch);
}
if (derivedStateFromCatch !== null && derivedStateFromCatch !== undefined) {

let derivedStateFromProps;
if (oldProps !== newProps) {
// In this case, the prevState parameter should be the partially updated state,
Copy link
Collaborator

Choose a reason for hiding this comment

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

Conceptually, what you're calling prevState is the work-in-progress state. So your comment here applies to all cases; it's not special.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

"in this case" just referred to the update case. The other two invocations of this method are mounting cases. But I'll re-word the comment.

// Otherwise, spreading state in return values could override updates.
derivedStateFromProps = callGetDerivedStateFromProps(
workInProgress,
instance,
newProps,
newState,
);
}

if (derivedStateFromProps !== null && derivedStateFromProps !== undefined) {
// Render-phase updates (like this) should not be added to the update queue,
// So that multiple render passes do not enqueue multiple updates.
// Instead, just synchronously merge the returned state into the instance.
newState =
newState === null || newState === undefined
? derivedStateFromCatch
: Object.assign({}, newState, derivedStateFromCatch);
? derivedStateFromProps
: Object.assign({}, newState, derivedStateFromProps);
}

if (
Expand Down