react新旧生命周期的区别?
1、新生命周期中去掉了三个will钩子,分别为componentWillMount、componentWillReceiveProps、componentWillUpdate;
2、新生命周期中新增了两个钩子,分别为getDerivedStateFromProps(从props中得到衍生的state)和getSnapshotBeforeUpdate。
react生命周期(旧):
react生命周期(新):
新的生命周期新增的两个钩子:
- getDerivedStateFromProps
- getSnapshotBeforeUpdate
1.getDerivedStateFromProps
getDerivedStateFromProps:从props中得到衍生的state
接受两个参数:props,state
会在调用 render 方法之前调用,即在渲染 DOM 元素之前会调用,并且在初始挂载及后续更新时都会被调用。
state 的值在任何时候都取决于 props。
getDerivedStateFromProps 的存在只有一个目的:让组件在 props 变化时更新 state。
该方法返回一个对象用于更新 state,如果返回 null 则不更新任何内容。
使用场景:若state的值在任何时候都取决于props,那么可以使用getDerivedStateFromProps
2.getSnapshotBeforeUpdate
getSnapshotBeforeUpdate:在更新前拿到快照(可以拿到更新前的数据)
在更新DOM之前调用
返回一个对象或者null,返回值传递给componentDidUpdate
componentDidUpdate():更新DOM之后调用
接受三个参数:preProps,preState,snapshotValue
废弃的原因:
在React16的Fiber架构中,调和过程会多次执行will周期,不再是一次执行,失去了原有的意义。此外,多次执行,在周期中如果有setState或dom操作,会触发多次重绘,影响性能,也会导致数据错乱。