Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
Set state takes a function #2991
This diff enables setState to accept a function in addition to a state partial. If you provide a function, it will be called with the up-to-date
This enables some nicer syntax for complex setState patterns:
If setState is doing an increment and wants to guarantee atomicy, you need a function:
This atomicy is particularly important if setState is called multiple times in a single frame of execution as the result of complex user actions. It's a tricky bug to chase down and difficult to determine how to fix when you find it. The current pattern of reaching into _pendingState relies on an implementation detail.
In this example: props.doAction() may result in your ancestor re-rendering and providing you with new props or context. If setState is called directly with an object literal referencing
Suggestion on how to approach the broken test? What conditions do we need to test there?
On Fri, Jan 30, 2015 at 8:30 PM, Sebastian Markbåge
I think that it is probably better to remove the piece from that test that introspects pending state. Then add another exhaustive test of this new setState-with-a-function. Then assert the sequencing of calling it in the various life cycles. As well as the sequencing of when the callbacks gets invoked. Including what this.state is at various life-cycles.
Just updated this pull to fix up ReactCompositeComponentState-test. It no longer inspects internal information and in order to test the same lifecycle of pending state, I added more setState() calls and a replaceState() call to ensure they're called in the correct order.
I think this should also cover the usages of providing a function.
We originally explored something like
We evaluated a bunch of options such as
@vjeux suggested that we'd just overload
We're also planning on overloading the API to accept a Promise anyway so this seems like a good start.
That said, I never really liked