前言
最近在尝试了解react,react更加考验编程功底和思维,和vue技术栈存在很大的差别。今天了解了一下react版本的差异。浅浅记录一下,方便自己以后回顾。
react 15
生命周期
初始化
constructor -> componentWillMount -> render -> componentDidMount -> componentWillUnmount
更新
componentWillReceiveProps(父组件更新) -> shoudleComponentUpdate (自身state更新) -> componentWillUpdate -> render ->componentDidUpdate
react 16
生命周期
初始化阶段
constructor -> getDerivedStateFromProps -> render -> componentWillUnmount
更新
getDerivedStateFromProps -> ->shoudleComponentUpdate -> render -> getSnapshotBeforeUpdate -> componentDidUpdate
getDerivedStateFromProps:
概念:一个静态方法static声明,接收两个参数props和自身的state,必须有返回值(对象格式)用于更新state内容,若无更新则返回null
用法:根据父组件的props的改变,更新自身的state
区别
### 生命周期
16中去掉了componentWillMount、componentWillReceiveProps、componentWillUpdate,分别用getDerivedStateFromProps和getSnapshotBeforeUpdate代替。getDerivedStateFromProps不是为了代替componentWillMount,而是代替componentWillReceiveProps
### 为什么有这样的修改?
15版本用的是stack reconciler 执行的时候是同步,不可被中断的。它是一个递归的过程,而js又是单线程,所以在执行组件渲染的时候,只有等底层执行完成之后,任务队列才会依次返回,最终全部执行完成才会进行渲染。整个过程中,无法存在其他线程来执行用户的其他交互。
例如,react15的这种运行机制,无法很优美的完成用户输入框,对应页面很快渲染的效果。从而会在用户体验上存在较大的瑕疵(即加载过程太多,从而造成的页面渲染卡顿问题,GUI与js执行是互斥的)。
16版本,针对于上述问题做了修改,改用了fiber架构,使用fiber reconciler,采用异步加载可随时中断,最后dom同步加载的方式。Scheduler(调度器)是这个架构新增的一层,主要是对reconciler的优先级进行调度,去检测浏览器什么时候有空闲时间执行程序。