1. React 中 setState 什么时候是同步的
Nobody has claimed this yet.
Assessment
- Difficulty
- 1/5
- Estimated time
- Under an hour
- Newbie friendliness
- 25/100
- Issue type
- Documentation
- Clarity
- Needs clarification
- Activity status
- Stale
- Tech stack
- react
- Domain
- frontend
Research direction
No repository file, test, or entry point is identified. Start by reviewing the issue text and its linked article about React setState batching; before making a change, clarify which documentation should be added or revised and what completed wording should cover.
Written by the indexing model from the issue text.
Description
在React中,如果是由React引发的事件处理(比如通过onClick引发的事件处理),调用setState不会同步更新this.state,除此之外的setState调用会同步执行this.state 。所谓“除此之外”,指的是绕过React通过addEventListener直接添加的事件处理函数,还有通过setTimeout/setInterval产生的异步调用。
原因:
在React的setState函数实现中,会根据一个变量isBatchingUpdates判断是直接更新this.state还是放到队列中回头再说,而isBatchingUpdates默认是false,也就表示setState会同步更新this.state,但是,有一个函数batchedUpdates,这个函数会把isBatchingUpdates修改为true,而当React在调用事件处理函数之前就会调用这个batchedUpdates,造成的后果,就是由React控制的事件处理过程setState不会同步更新this.state。
注意:
setState的“异步”并不是说内部由异步代码实现,其实本身执行的过程和代码都是同步的,只是合成事件和钩子函数的调用顺序在更新之前,导致在合成事件和钩子函数中没法立马拿到更新后的值,形式了所谓的“异步”,当然可以通过第二个参数 setState(partialState, callback) 中的callback拿到更新后的结果。
详细请看 深入 setState 机制
- Dominant language
- HTML
- Stars
- 1
- Forks
- 0
- PR merge metrics
- No merged PRs in 30d
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
More from AstralBit/NOTE
-
Fiber reconciler Open
Difficulty 1/5 Under an hour Newbie friendliness 25/100
-
JS深入浏览器缓存分强缓存和协商缓存 Open
Difficulty 1/5 Under an hour Newbie friendliness 25/100
-
深入理解React fiber Open
Difficulty 5/5 Over a week Newbie friendliness 25/100
-
Javascript深入垃圾回收 Open
Difficulty 5/5 Over a week Newbie friendliness 20/100
-
JavaScript深入闭包 Open
Difficulty 5/5 Over a week Newbie friendliness 25/100
Similar issues
-
Browser Waiting for: Product Owner
Difficulty 2/5 1-3 hours Newbie friendliness 85/100
getsentry/sentry-javascript#24577 · 1 comment ·
-
1.0.0-alpha2 Type/Improvement
Difficulty 2/5 1-3 hours Newbie friendliness 68/100
wso2/dpdp-accelerator#272 ·
-
light
Difficulty 2/5 1-3 hours Newbie friendliness 85/100
aemdemos/patients-stryker#253 ·
-
Difficulty 2/5 1-3 hours Newbie friendliness 86/100
clerk/javascript#9852 ·
-
bug good first issue
Difficulty 2/5 1-3 hours Newbie friendliness 88/100
amponce/archive-movie-browser#165 ·