React学习第四天(生命周期)

160 阅读1分钟

生命周期

旧版本生命周期图

image.png

1.初始化阶段:由ReactDOM.render触发--初次渲染

  1. constructor 触发构造器
  2. componentWillMount 组件将要挂载
  3. render 将组件放入页面
  4. componentDidMount 组件挂载完成 (比较常用 进行初始化操作 请求数据 开启定时器 订阅消息)

更新阶段:由组件内部this.setState或父组件redner触发

  1. shouldComponentUpdate 判断是否更新数据的开头 默认是true /可以自己更改 返回一个boolean值 /false则不会触发视图的更新

  2. componentWillUpdate 组件将要更新

  3. render 更改视图状态

  4. componentDidUpdate 更新完成

强制更新:forceUpdate 依次执行 2->3->4这3个钩子函数

卸载组件:由ReactDOM.unmountComponentAtNode 触发

  1. componentWillUnmount 组件将要卸载 (一般在此钩子函数里面执行收尾操作:关闭定时器 取消订阅)

新版生命周期

image.png

新旧两者之前对比

新版本增加了两个生命周期

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 子组件数据更新执行 (第一次参数获取不执行)