生命周期
旧版本生命周期图
1.初始化阶段:由ReactDOM.render触发--初次渲染
constructor触发构造器componentWillMount组件将要挂载render将组件放入页面componentDidMount组件挂载完成 (比较常用 进行初始化操作 请求数据 开启定时器 订阅消息)
更新阶段:由组件内部this.setState或父组件redner触发
-
shouldComponentUpdate判断是否更新数据的开头 默认是true /可以自己更改 返回一个boolean值 /false则不会触发视图的更新 -
componentWillUpdate组件将要更新 -
render更改视图状态 -
componentDidUpdate更新完成
强制更新:forceUpdate 依次执行 2->3->4这3个钩子函数
卸载组件:由ReactDOM.unmountComponentAtNode 触发
componentWillUnmount组件将要卸载 (一般在此钩子函数里面执行收尾操作:关闭定时器 取消订阅)
新版生命周期
新旧两者之前对比
新版本增加了两个生命周期
getDerivedStateFromProps 得到一个派生的状态 在shouldComponentUpdate前执行,具体实际开发中用处不大,可以接收props参数,返回一个null或者是个对象,需要被定义成静态方法
static getDerivedStateFromProps(props){
console.log(props);
return null
}
getSnapshotBeforeUpdate 在更新之前获取快照,获取上一个实例对象的数据
getSnapshotBeforeUpdate(){
return this.refs.list.scrollTop
}
componentDidUpdate(preProps,preState,height){
this.refs.list.scrollTop+=this.refs.list.scrollHeight+height
}
getSnapshotBeforeUpdate返回的值,可以在componentDidUpdate函数里面接收到
废弃了三个钩子
componentWillMount组件将要挂载componentWillUpdate组件将要更新componentWillReceiveProps子组件数据更新执行 (第一次参数获取不执行)