React生命周期主要会经历这4个阶段:创建阶段、实例化阶段、更新阶段、销毁阶段

- 调用
React.createClass,即创建组件类的时候,会触发getDefaultProps方法,该方法返回一个对象,然后与父组件指定的props对象合并,最后赋值给this.props作为该组件的默认属性,该方法只调用一次
2、实例化阶段
-
getInitialState:初始化state的值,返回值会赋给this.state -
componentWillMount:操作state,不会触发再次渲染,建议用constructor代替 -
render:根据 state 的值,生成页面需要的虚拟 DOM 结构 -
componentDidMount:可以设置state,会触发再次渲染,组件内部可以通过ReactDOM.findDOMNode(this)来获取当前组件的节点操作DOM
3、更新阶段~~用户操作或者父组件有更新的时候
-
componentWillReceiveProps(nextProps):当组件接收到新的props时会触发该函数,通常可以调用this.setState方法来比较this.props和nextProps的执行状态,完成对state的修改 -
shouldComponentUpdate(nextProps, nextState):该方法用来拦截新的props或state,然后判断是否更新组件 -
componentWillUpdate(nextProps, nextState):更新之前调用 -
render:根据diff算法,生成需要更新的虚拟DOM数据 -
componentDidUpdate(prevProps, prevState):更新之后调用,可以进行DOM 操作
tips:render中最好只是数据和模板的组合,不应该修改state
如果shouldComponentUpdate返回false,componentWillUpdate,render,componentDidUpdate都不会被调用
4、销毁阶段
- 会触发
componentWillUnmount,通常是移除DOM,取消事件绑定,销毁定时器等工作
props
- 1、
props是一个对象,是组件用来接收外面传来的参数的 - 2、组件内部是不允许修改自己的
props属性,只能通过父组件来修改
state
- 它是用来存储组件自身需要的数据
- 它是可以改变的,它的每次改变都会触发组件的
render方法来更新DOM结构
递归调用~Will方法先调用,Did方法后调用
- 父组件的
componentWillMount / componentWillUpdate方法一定在子组件的componentWillMount / componentWillUpdate方法之前调用 - 父组件的
componentDidMount / componentDidUpdate方法一定在子组件的componentDidMount / componentDidUpdate方法之后调用
参考文章推荐:
深入理解react(源码分析) #1
React源码分析3 — React生命周期详解
React 源码剖析系列 - 生命周期的管理艺术
React生命周期的实现
React.Component
React - 组件的生命周期详解(及各阶段调用的方法)