innerWang / blogs

1 stars 0 forks source link

简单介绍下React的生命周期 #1

Open innerWang opened 5 years ago

innerWang commented 5 years ago

----报几个钩子函数,按照顺序,按挂载/更新区分 ----各个阶段都做了什么?

innerWang commented 5 years ago

React 组件的生命周期包含三个阶段: 装载过程,更新过程,卸载过程。

1. 装载过程

依次调用如下生命周期函数:

* constructor      // 初始化state 以及 绑定成员函数的 this 环境(React组件的方法默认不绑定this)
* componentWillMount    // 主要为了和 DidMount 对称???
* render        // 返回一个JSX描述的结构,由React来操作渲染过程,render无默认实现,需要用户实现。
* componentDidMount    // 只能在浏览器端被调用,调用此函数时,render返回的数据已经引发渲染,组件已经被“装载”到 DOM 树上。
2. 更新过程

依次调用如下生命周期函数:

* componentWillReceiverProps   //当props被改变或者父组件render函数被调用时,此函数都会被调用,通过setState触发的更新过程不会调用此函数
* shouldComponentUpdate    // 允许手动判断是否要进行组件渲染,避免不必要的渲染
* componentWillUpdate  
* render                    
* componentDidUpdate    //与装载过程不同,无论更新发生在服务器端还是浏览器端,该函数都会调用
3. 卸载过程
* componentWillUnmount   //调用此函数就会将组件从DOM树上删除

code

innerWang commented 5 years ago

通常我们在组件的componentDidMount函数中发送请求获取服务器的资源,这是因为 React16 之后采用了Fiber架构,只有componentDidMount生命周期函数是确定被执行一次的,类似ComponentWillMount的生命周期钩子都有可能执行多次。