the subject reads this article:
< H1 >
https://zhuanlan.zhihu.com/p/.
fellow countrymen.
I knew that setState was asynchronous, but I didn't know its internal mechanism or when render was triggered. In order to read the source code, it is a pity that I have not been able to find out the details of the Fiber update, the difficulty of reading has increased suddenly, until today, I still do not understand all of it, but I have some of my own understanding of the general mechanism. Here, I would like to talk about my personal views. At the same time, I hope to have a great god who knows more about the internal mechanism, such as Szeto Zhengmei.
=
first of all, make it clear that "async" means "re-render is not triggered every time setState". In fact, the upstairs answer is already related to the implementation principle, that is, the essence of setState is to update a queue, and then calculate the state, to trigger the update based on the queue content in the subsequent logic.
take the update process of class component as an example, you can roughly see the specific implementation. Click on the link to view the complete code. Here is an excerpt of the code analysis:
componentWillReceivePropssetStatecwr
updateClassInstance
re-render is done here. So we can see that setState and render are completely separate. Render will be unified only after the end of the life cycle that should be left behind.
the internal implementation of setState has not been introduced here. You can take a look at it for yourself. You can skip the fiber scheduling section and you can probably see that you are updating the queue. (I'm going for a run. I don't have time to write.)
You can learn about the concepts of updateQuque and transaction machine in
react. Because the fault-tolerant mechanism of react itself is very good, if you trigger the setState operation when you enter the life cycle after setState, react will not report an error, but will push forward to the next batchUpdate and mark a series of dirtyComp, to process again in the subsequent transaction cycle
paste the preact source code for you
function setState(state, callback) {
let s = this.state;
if (!this.prevState) this.prevState = extend({}, s);
extend(s, typeof state==='function' ? state(s, this.props) : state);
if (callback) this._renderCallbacks.push(callback);
enqueueRender(this);
}
function enqueueRender(component) {
if (!component._dirty && (component._dirty = true) && items.push(component)==1) {
(options.debounceRendering || defer)(rerender); //
}
}
finish