I realize that calling setState
does not update this.state
immediately, nor does it immediately call render
and refresh the DOM. The docs say
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value.
There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
I would like to be able to force a "state transition" like this at any point. This seems like it ought to be a fairly natural operation, but I can't find any mention of it in the docs. Is there a way to do it?
You can use forceUpdate
for this:
If your render() method reads from something other than this.props or this.state, you'll need to tell React when it needs to re-run render() by calling forceUpdate(). You'll also need to call forceUpdate() if you mutate this.state directly.
https://facebook.github.io/react/docs/component-api.html#forceupdate
You can use a forceUpdate
in conjunction with having a key on the top level component as so..
let key= 0;
var Hello = React.createClass({
sudoForceUpdate(){
key++;
this.forceUpdate();
},
render: function(){
return <div key={key}>Example</div>;
}
});
By editing the key and forcing an update, the dom will always rerender.
Here is an example that highlights the difference between just a force edit, and one with a key change*.
https://jsfiddle.net/69z2wepo/82763/
*note that this is likely pretty bad practice.
Thanks to Ben Alpert: https://groups.google.com/forum/#!topic/reactjs/8JgClU9jol0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With