# React生命周期执行顺序
//组件加载的时候
constructor(props){
super(props)
this.state = {
msg:'君陌离'
}
}
//组件将要挂载
componentWillMount(){
}
//数据渲染
render(){
}
//组件挂载完成的时候
componentDidMount(){
}
//组件数据更新的时候
//是否需要更新
shouldComponentUpdate(){
return true
}
//将要更新
componentWillUpdate(){
}
//更新完成
componentDidUpdate(){
}
render(){
}
//父组件里面改变props传值的时候出发
componentWillReceiveProps(){
}
//组件销毁
componentWillUnmount(){
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# react 生命周期详解
第一步:
初始化阶段,即(constructor()),继承了基类,才会有render()方法,生命周期才能使用。【这也是为什么函数组件不能使用这些方法的原因!!】;super(),用来调用基类的构造方法,将父组件的props注入子组件【props只读,不可变;state可变】第二步:
挂载阶段,componentWillMount()挂载前,调用一次,这里调用this.state不会引起组件重新渲染【这里的内容可以提到constructor中,所以很少使用】;render()根据props和state,render一个UI,不负责实际渲染,之后由React自身根据此元素去渲染出DOM。render是纯函数,不能在里面执行this.setState(),会有改变组件状态的副作用!;componentDidMount():组件挂载到DOM后调用,方法会在组件已经被渲染到 DOM 中后运行,只会调用一次!第三步:
组件更新阶段,【⚠️setState引起的state更新、父组件重新render引起的props更新,更新后的state、props无论是否有变化都会引起子组件重新更新render!!这里可以用shouldComponentUpdate()来优化】;componentWillReceiveProps(nextProps)此方法只调用于props引起的组件更新过程中,参数nextProps是父组件传给当前组件的新props,在此方法中来查明重传的props是否改;将props转化成自己的state【在这里调用this.setState()将不会引起第二次渲染!】因为此方法会判断props是否变化了,若变化了this.setState()将引起state变化,进而引起render变化,此时就没必要在做第二次因重传props引起的render了;shouldComponentUpdate(nextProps, nextState)返回true继续执行,false阻止组件更新,减少不必要的渲染,优化性能;就算上一个方法执行了this.state更新了state,但在render之前此方法中的this.state依然指向更新之前的!!!,否则就永远是true了;componentWillUpdate(nextProps, nextState)在render之前执行,进行更新前的操作,比较少用;render()重新调用componentDidUpdate(prevProps, prevState)此方法在组件更新后被调用,可以操作组件更新的DOM,prevProps和prevState指组件更新前的props和state;第四步:
卸载阶段:componentWillUnmount()在组件被卸载前调用,可以执行一些清理工作,如清除定时器,清除挂载后手动创建的DOM,避免内存泄漏。
# react生命周期执行顺序
只执行一次: constructor、componentWillMount、componentDidMount
执行多次:render 、子组件的componentWillReceiveProps、componentWillUpdate、componentDidUpdate
有条件的执行:componentWillUnmount(页面离开,组件销毁时)
不执行的:根组件(ReactDOM.render在DOM上的组件)的componentWillReceiveProps(因为压根没有父组件给传递props)