In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What is the usage of setState? for this question, this article introduces the corresponding analysis and answer in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.
Is setState synchronous or asynchronous?
First of all, with the throwing of this question, I will think, why should I throw out this question? If you need to rely on the value after the status update, what should you do first?
For Class Component, we can do it in the componentDidMount or componentDidUpdate phase.
In the case of Function Component, we can execute it in the callback function of useEffect.
First of all, we first come to the conclusion that the situation is different for different modes in React, mainly taking two modes.
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Legacy mode
Concurrent mode
Legacy mode
This is the method currently used by React app.
ReactDOM.render (, rootNode)
There are currently no plans to delete this mode, but this mode may not support these new features.
Back to our above question, is setState synchronous or asynchronous?
When batchedUpdates is hit in legacy mode, setState is asynchronous.
When the batchedUpdates is missed in legacy mode, the setState is synchronized.
Now that we've come to this point, let's talk about the role of the batchedUpdates function.
So what does it do? If you call this.setState multiple times in a processing logic function, how does it update the state?
This.setState ({value: this.state.value + 1}) this.setState ({value: this.state.value + 1}) this.setState ({value: this.state.value + 1})
So React implements this batch update operation, merging multiple setState into one update, so how does it achieve it? the batchedUpdates function comes on stage.
Function batchedUpdates$1 (fn, a) {var prevExecutionContext = executionContext; executionContext | = BatchedContext; try {return fn (a);} finally {executionContext = prevExecutionContext; if (executionContext = NoContext) {/ / Flush the immediate callbacks that were scheduled during this batch resetRenderTimer (); flushSyncCallbackQueue (); / / synchronized updates}
This function passes a fn, and before executing fn, it appends a BatchedContext to the executionContext variable, and when the fn is finished, executionContext removes the previous BatchedContext tag.
In this way, when the executionContext is marked with BatchedContext, the react will judge and wear this tag, and this update is batch, so this update is asynchronous.
So, can we assume that if we update the status after executing the fn function, can we complete the synchronous update?
SetTimeout function, we can put setState in the timer, so that when the fn function is finished, the BatchedContext tag is removed, and then wait until the callback function of setTimeout is idle to execute setState.
SetTimeout (() = > {this.setState ({value: this.state.value + 1})}, 0)
That is, when executionContext = NoContext, that is, the flushSyncCallbackQueue function is executed to complete the synchronous update.
Of course, in concurrent mode, it's different again.
At this point, we need to talk about the scheduleUpdateOnFiber function.
We all know that the starting point of task scheduling is the scheduleUpdateOnFiber method, and the dispatchAction of React.render, setState, forceUpdate, and React Hooks all passes through scheduleUpdateOnFiber.
Function scheduleUpdateOnFiber (fiber, lane, eventTime) {/ /. If (root = = workInProgressRoot) {/ /. } / / TO an argument to that function and this one. If (lane = SyncLane) {/ / synchronization task if (/ / check whether it is currently in unbatchedUpdates (non-batch update), (the first rendered ReactDOM.render is unbatchedUpdates) (executionContext & LegacyUnbatchedContext)! = NoContext & & / / Check if we're not already rendering (executionContext & (RenderContext | CommitContext)) = NoContext) {/ / Register pending interactions on the root to avoid losing traced interaction data. SchedulePendingInteractions (root, lane); performSyncWorkOnRoot (root);} else {ensureRootIsScheduled (root, eventTime); schedulePendingInteractions (root, lane); if (executionContext = NoContext) {resetRenderTimer (); flushSyncCallbackQueue ();} else {/ / asynchronous task / / concurrent mode is flushSyncCallbackQueue synchronous update / /. }}
The scheduleUpdateOnFiber function uses lane = SyncLane to determine whether it is a synchronous task or an asynchronous task. The React app created by ReactDom.render () will enter this judgment, but in concurrent mode, it is different, so how is it created?
Concurrent mode
You can understand that this is still an experimental stage, when the future is stable, it will be the default development mode of React development, how does it create a React App application?
ReactDOM.createRoot (rootNode) .render ()
This mode turns on all the new features.
Status updates in concurrent mode are asynchronous.
If you are interested in interpreting React's concurrent schema, you can take a look at the official documentation.
At this point, it seems that we know something about whether the setState in React is synchronous or asynchronous.
Which will hit the batchUpdate mechanism
Life cycle (and it calls functions)
Events registered in React
React can 'manage portals'
The answers to the questions about the use of setState are shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel for more related knowledge.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.