在React类组件中,生命周期函数是贯穿整个React程序运行周期的函数,继承React.Component中,不需要单独调用。虽然现在多数新的React项目用函数组件较多,但还是很多老项目由大量的类组件构成(比如我现在工作维护的项目)所有对生命周期函数有个全面的了解是很重要的
React生命周期函数(旧版)
在旧版React生命周期函数中,一共有9个函数(如图所示),分别为:
- constructor
- render
- componentDidMount
- componentWillUnmount
- componentDidUpdate
- componentWillUpdate
- shouldComponentUpdate
- componentWillReceiveProps
先是组件第一次挂载时,
- constructor构造器是class中自带的属性,在class生成时加载,对应React就是React类组件生成时就完成加载了,里面通常定义state,接受props以及调用super()方法等
- render方法在组件第一次挂载和组件更新都会调用
- 组件第一次完成挂载(渲染)时会调用componentDidMount,一般用来发送http请求,定时器等初始化工作
- componentWillUnmount会在组件将被摧毁之前调用
组件完成第一次挂载后的更新阶段,
- 当接收的props发生改变调用componentWillReceiveProps函数
- shouldComponentUpdate在渲染之前调用,默认返回true
- 每一组件的重新渲染就会调用componentWillUpdate
- 重新渲染之后调用componentDidUpdate,首次挂载不会调用
React生命周期函数(新版)
- getDerivedStateFromProps 代替了componentWillReceiveProps
- getSnapshotBeforeUpdate 代替了componentWillUpdate
新版本的两个函数代替了老版本的,比如在 getDerivedStateFromProps 中禁止了组件去访问 this.props,强制让开发者去比较 nextProps 与 prevState 中的值。getSnapshotBeforeUpdate() - 这个方法在最新的render输出被提交给DOM前将会立即调用。它使得组件能在发生更改之前从DOM中捕获一些信息(例如滚动位置)。此生命周期的任何返回值将作为参数传递给componentDidUpdate()。
注意:React团队已经宣布componentWillMount,componentWillReceiveProps,和componentWillUpdate这三个生命周期方法在React 17.0之后将被废弃,并推荐使用新的生命周期方法替代。