React生命周期

485 阅读1分钟

1、顺序

1.1、初始阶段

  • componentWillMount 组件被渲染到页面之前触发
  • render 组件渲染
  • componentDidMount 组件已经被渲染到页面中后触发

1.2、运行阶段

  • componentWillReceiveProps 组件即将接收到新属性时触发
  • shouldComponentUpdate 组件接受新属性,或状态改变时触发,首次渲染不触发
如果使用了mobx的observer,会报错:
It is not allowed to use shouldComponentUpdate in observer based components.
  • componentWillUpdate 组件即将被更新时触发
  • componentDidUpdate 组件更新完成后触发

1.3、销毁阶段

  • componentWillUnmount 组件被销毁时触发
代码示例:
    componentWillReceiveProps() {
        console.log('componentWillReceiveProps');
    }

    shouldComponentUpdate(newProps, newState) {
        console.log('shouldComponentUpdate');
    }

    componentWillUpdate() {
        console.log('componentWillUpdate');
    }

    componentDidUpdate() {
        console.log('componentDidUpdate');
    }

    componentWillUnmount() {
        console.log('componentWillUnmount');
    }

    render() {
        console.log('render');
        return (
                <p>Test</p>
        )
    }
    
    //结果
    componentWillMount //初始化
    render
    componentDidMount
    
    componentWillReceiveProps //运行阶段
    componentWillUpdate
    render
    componentDidUpdate
    
    componentWillUnmount //销毁阶段

2、问题

2.1、组件什么时候被销毁?

“组件的销毁隐匿于父组件的render函数中。当父组件执行render函数时,某些情况下,Virtual DOM中的某些节点经过diff,发现已经不存在了,因此会被销毁,而这个节点正好是一个组件的话,那么组件就会被销毁。”

class M extends Component {
  render() {
    return (
      <div>
        {this.props.renderMyComponent ? <MyComponent /> : null}
      </div>
    )
  }
}
// M组件发生更新,当renderMyComponent这个属性为false时,MyComponent这个组件就会被销毁,它的componentWillUnmount就会被调用。
参考: