azl397985856 / fe-interview

宇宙最强的前端面试指南 (https://lucifer.ren/fe-interview)
Apache License 2.0
2.84k stars 260 forks source link

【每日一题】- 2020-01-23 - unstable_batchedUpdates是什么?解决了什么问题?原理是什么? #100

Closed azl397985856 closed 4 years ago

azl397985856 commented 4 years ago

react新版本有一个不稳定的APIunstable_batchedUpdates 用来做批量更新, 为什么要开发这个API?解决了什么问题?什么情况下应该使用?原理是怎样的?

azl397985856 commented 4 years ago

unstable_batchedUpdates 就如同 react内部的批量更新state算法batchUpdate,其本质也是对多次state修改批量更新,效果是多次render合并到一次。 而unstable_batchedUpdates也是类似的效果,只不过有一个地方不同:这个是暴露给开发者的方法,而batchUpdate是框架内部方法。

说到unstable_batchedUpdates的用途我们要知道一个先行知识点。 那就是react对于组件内部的setState引起的state变更默认会走批量更新,但是对于外部引起的变化不会,比如ajax回调函数引起的状态变化。 那么如何让诸如ajax回调函数引起的状态变化也走“批量更新”逻辑呢? unstable_batchedUpdates提供了这种可能。

最后说一下原理,实际上unstable_batchedUpdates只不过batchupdate算法对外的暴露。 而搞懂batchUpdate方法又要先懂得“react中事物机制”,如果不清楚建议先看一下相关内容。 如果你想简单理解,可以这么理解“react内部设置了一个bool变量,用来判断给定时间内的组件是否发生了变化。 如果发生了变化,我们最后一起更新” 实际上这个解释很不严谨,但是不影响理解和使用。

stale[bot] commented 4 years ago

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.