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

setState() in componentDidMount() should flush synchronously even with createBatch() #12466

Merged
merged 6 commits into from
Mar 29, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
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
40 changes: 40 additions & 0 deletions packages/react-dom/src/__tests__/ReactDOMRoot-test.internal.js
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,46 @@ describe('ReactDOMRoot', () => {
expect(container.textContent).toEqual('Hi');
});

it('applies setState in componentDidMount synchronously in a batch', done => {
class App extends React.Component {
state = {mounted: false};
componentDidMount() {
this.setState({
mounted: true,
});
}
render() {
return this.state.mounted ? 'Hi' : 'Bye';
}
}

const root = ReactDOM.createRoot(container);
const batch = root.createBatch();
batch.render(
<AsyncMode>
<App />
</AsyncMode>,
);

flush();

// Hasn't updated yet
expect(container.textContent).toEqual('');

let ops = [];
batch.then(() => {
// Still hasn't updated
ops.push(container.textContent);

// Should synchronously commit
batch.commit();
ops.push(container.textContent);

expect(ops).toEqual(['', 'Hi']);
done();
});
});

it('does not restart a completed batch when committing if there were no intervening updates', () => {
let ops = [];
function Foo(props) {
Expand Down
12 changes: 11 additions & 1 deletion packages/react-reconciler/src/ReactFiberScheduler.js
Original file line number Diff line number Diff line change
Expand Up @@ -1169,7 +1169,15 @@ export default function<T, P, I, TI, HI, PI, C, CC, CX, PL>(
interruptedBy = fiber;
resetStack();
}
if (nextRoot !== root || !isWorking) {
if (
// If we're in the render phase, we don't need to schedule this root
// for an update, because we'll do it before we exit...
!isWorking ||
isCommitting ||
// ...unless this is a different root than the one we're rendering.
nextRoot !== root
) {
// Add this root to the root schedule.
requestWork(root, expirationTime);
}
if (nestedUpdateCount > NESTED_UPDATE_LIMIT) {
Expand Down Expand Up @@ -1500,6 +1508,8 @@ export default function<T, P, I, TI, HI, PI, C, CC, CX, PL>(
nextFlushedRoot = root;
nextFlushedExpirationTime = expirationTime;
performWorkOnRoot(root, expirationTime, false);
// Flush any sync work that was scheduled by lifecycles
performSyncWork();
finishRendering();
}

Expand Down