目录
生命周期
函数列表
重要生命周期函数细解
分阶段看钩子的执行顺序(图解)
一、生命周期
生命周期就是指一个对象的生老病死。
在
React
中就特指一个组件的“生老病死”。
二、函数列表
constructor()
– 初始化 state 等- static getDerivedStateFromProps()
shouldComponentUpdate()&React.PureComponent
– 是否进行更新render()
– 创建虚拟 DOM- getSnapshotBeforeUpdate
componentDidMount()
– 组件已出现在页面componentDidUpdate()
– 组件已更新componentDidWillUnmount()
– 组件将死- static getDerivedStateFromError()
- componentDidCatch()
三、重要生命周期函数细解
1、constructor
参数
constructor(props);
用途
- 初始化 props
- 初始化 state,但
此时不能调用setState
- 用来写
bind this
constructor(){
/* 省略不必要的代码 */
this.οnclick=this.onclick.bind(this)
}
// 可用以下新语法代替
constructor(){
/* 省略其他不必要的代码 */
}
οnclick=()=>{}
- 可不写,但写了就必须写全
2、shouldComponentUpdate
参数
shouldComponentUpdate(nextProps, nextState)
# next就是new => 就是新的数据
-
作用
它允许我们手动判断是否要进行组件更新,我们可以根据应用场景灵活设置返回值,以避免不必要的更新。
-
用途
- 返回 true 表示让 UI 更新
- 返回 false 表示阻止 UI 更新
将newState的每个属性和this.state作对比,某个不等就更新,否则不更新。
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
n: 1,
};
}
shouldComponentUpdate(newProps, newState) {
if (newState.n === this.state.n) {
return false;
} else {
return true;
}
}
}
React.PureComponent:
这个是上面自己判断是否要更新的语法糖,如果继承的是 React.PureComponent 而不是 React.Component。那么它会自己判断是否需要更新(还是通过数据是否变化)
3、render
用途
- 展示视图
return(<div>....</div>)
- 写的 HTML 只要一个根元素
- 如果 HTML 有多个根元素,需要用
<React.Fragment></React.Fragment>
包起来,可以缩写为<></>
技巧
- render 里面可以写
if...else语句
- render 里面可以写
?:表达式
- render 里面
不能直接写for循环,要用数组
- render 里面可以写
array.map(循环)
4、componentDidMount
参数
componentDidMount();
用途
- 在元素插入页面后执行代码,这些代码依赖 DOM
此处可以发起加载数据的AJAX请求(官方推荐)
- 首次渲染会执行此钩子
- 你如果想获取 div 的高度,最好在这里写
5、componentDidUpdated
参数
componentDidUpdate(prevProps, prevState, snapshot);
用途
- 在视图更新后执行代码
- 此处也可发起 AJAX 请求,用于
更新数据
- 首次渲染不会执行此钩子
在此处setState可能会引起死循环(除了判断条件后)
- 若 shouldComponentUpdated()返回 false,则不会触发此钩子
6、componentWillUnmount
参数
componentWillUnmount();
用途
- 组件将要
被移除页面然后被销毁
时执行的代码 unmount过的组件不会再次mount
-
注意事项
如果你在组件
componentDidMount中创建监听事件,计时器,AJAX请求等等
。那么你就要在该组件componentWillUnmount中取消监听事件,计时器AJAX请求等等
原则:处理不必要的垃圾内存!