react 的生命周期
react 的生命周期,可能经过三个过程:
- 装载 mount
- 更新 update
- 卸载 unmount
装载 mount
当组件第一次被装载的时候,react 会依次调用如下函数
- constructor
- getInitialState:一般不会用到,state 一般在constructor 中进行初始化
- getDefaultProps
- componentWillMount
- render
- componentDidMount
constructor
constructor 阶段的主要作用是:
- 初始化 state
- 给类的方法bind this
getDefaultProps
在es6 中我们需要这样来给props赋默认值
1 | class Sceen extends React.component{ |
render
在生命周期中只有render是必须实现的函数,它只是返回一个 jsx 描述的结构,最终由react来进行渲染。如果返回null 或者 undefined ,就等于告诉react不用进行渲染
componentWillMount 和 componentDidMount
一般来说componentWillMount用的比较少,componentDidMount 用的比较多一点
需要注意的是:componentDidMount 是发生在组件已经挂载到 dom 上触发的
更新 update
更新的生命周期主要有以下几个:
- componentWillReceiveProps
- shouldUpdateComponent
- componentWillUpdate
- render
- componentDidUpdate
componentWillReceiveProps
这里需要注意的几点是:
- 当父组件的render 被调用的时候,子组件的 componentWillReceiveProps 也会被触发,不管子组件的props是否发生了更新
- 在组件中setState并不会触发这一生命周期
shouldUpdateComponent
这是组件中最重要的一个生命周期了,它决定了组件是否需要重新渲染。
需要注意的是,setState并不会立即修改组件的state,在这一周期的时候组件的state还是原来的。
componentWillUpdate 和 componentDidUpdate
会在render的一前一后进行触发,componentDidUpdate 和 componentDidMount一样也是在dom重新渲染之后触发的。
卸载 unmount
在销毁组件之前,会触发,componentWillUnmount,这个钩子适合用来处理一些清除性的工作。