React 生命周期概括及详解

379 阅读2分钟

React 组件的生命周期概括

React 组件的生命周期可分成三个状态:

  • Mounting:已插入真实 DOM(创建时)
  • Updating:正在被重新渲染(更新时)
  • Unmounting:已移出真实 DOM(卸载时)

Mounting(创建时)

  1. constructor() //constructor构造函数
  2. static getDerivedStateFromProps(props, state) //获取派生状态,接受新属性执行
  3. componentWillMount() //组件将要加载,(不建议使用,即将废弃)
  4. render() //创建虚拟dom更新dom树
  5. componentDidMount() //组件挂载完成

Updating(更新时)

  1. componentWillReceiveProps() //组件将接受新的props(不建议使用,即将废弃)
  2. static getDerivedStateFromProps()
  3. shouldComponentUpdate(nextProps, nextState) //组件是否更新
  4. componentWillUpdate() //组件将要更新(不建议使用,即将废弃)
  5. render()
  6. getSnapshotBeforeUpdate() //获取快照
  7. componentDidUpdate() //组件更新完成

Unmounting(卸载时)

  1. componentWillUnmount() //组件将要卸载

React 生命周期方法流程详解

生命周期流程

生命周期方法

1. static defaultProps

设置默认的props

例:

static defaultProps = {
    name:'张三'
}

2. constructor()

构造函数,可以继承父级属性及设置state状态

constructor(props){
    super();
    this.state = {age:20};
}

3. componentWillMount()

组件将要挂载,组件初始化时调用,以后组件更新不调用,整个生命周期只调用一次,此时可以修改state。

4. render()

react最重要的步骤,创建虚拟dom,进行diff算法,更新dom树都在此进行。

render(){
    return(
    <div>
        <p>{this.state.name}</p>
    </div>    
    )
}

5.componentDidMount()

组件挂载完毕,组件渲染之后调用,只调用一次。

componentDidMount(){
    console.log('组件挂载完成');
}

6. componentWillReceiveProps()

接收到新的属性后才可以执行,第一次不会执行

componentWillReceiveProps(nextProps){
    console.log('新的属性')
}

7. shouldComponentUpdate()

控制状态变化后 是否更新视图,返回true更新,返回false不更新,react性能优化非常重要的一环。

shouldComponentUpdate(nextProps,nextState){
    return true;//默认为true
    return nextState.name !==this.state.name; //如果此函数种返回了false 就不会调用render方法了
}

8. componentWillUpdate()

组件将要更新,组件初始化时不调用,只有在组件将要更新时才调用

componentWillUpdate(){
    console.log('组件将要更新');
}

9. componentDidUpdate()

组件完成更新,组件初始化时不调用,组件更新完成后调用,此时可以获取dom节点。

componentDidUpdate(){
    console.log('组件更新完成');
}

10. componentWillUnmount()

组件将要卸载时调用,一些事件监听和定时器需要在此时清除。

componetWillUnmount(){
    console.log('组件将要卸载');
}

总结

以上就是React 生命周期的总流程,想要更详细的了解大家参考React 官网API,欢迎留言交流。