zoukankan      html  css  js  c++  java
  • 21 React生命周期整理流程图

    React Component,就像人会有生老病死一样有生命周期。一般而言 Component 有以下三种生命周期的状态:

    1. Mounting:已插入真实的 DOM
    2. Updating:正在被重新渲染
    3. Unmounting:已移出真实的 DOM

    针对 Component 的生命周期状态 React 也有提供对应的处理方法:

    1. Mounting
      • componentWillMount()
      • componentDidMount()
    2. Updating
      • componentWillReceiveProps(object nextProps):已载入组件收到新的参数时呼叫
      • shouldComponentUpdate(object nextProps, object nextState):组件判断是否重新渲染时呼叫,起始不会呼叫除非呼叫 forceUpdate()
      • componentWillUpdate(object nextProps, object nextState)
      • componentDidUpdate(object prevProps, object prevState)
    3. Unmounting
      • componentWillUnmount()

            很多读者一开始学习 Component 生命周期时会觉得很抽象,所以接下来用一个简单范例让大家感受一下 Component 的生命周期。读者可以发现当一开始载入组件时第一个会触发 console.log('constructor');,依序执行 componentWillMountcomponentDidMount ,而当点击文字触发 handleClick() 更新 state 时则会依序执行 componentWillUpdatecomponentDidUpdate

    class MyComponent extends React.Component {
      constructor(props) {
        super(props);
        console.log('constructor');
        this.handleClick = this.handleClick.bind(this);
        this.state = {
          name: 'Mark',
        }
      }
      handleClick() {
        this.setState({'name': 'Zuck'});
      }
      componentWillMount() {
        console.log('componentWillMount');
      }
      componentDidMount() {
        console.log('componentDidMount');
      }
      componentWillReceiveProps() {
        console.log('componentWillReceiveProps');
      }
      componentWillUpdate() {
        console.log('componentWillUpdate');
      }
      componentDidUpdate() {
        console.log('componentDidUpdate');
      }
      componentWillUnmount() {
        console.log('componentWillUnmount');
      }
      render() {
        return (
          <div onClick={this.handleClick}>Hi, {this.state.name}</div>
        );
      }
    }
    
    ReactDOM.render(<MyComponent />, document.getElementById('app'));

            下面是一张React组件生命周期的流程图整理图:

  • 相关阅读:
    学习Extjs4 (21) 简单窗口
    C#启动外部程序的几种方法以及等待外部程序关闭的方法
    linux驱动学习(3)同步、信号量和自旋锁
    andoird webiew使用有道辞典实例
    Linux程序设计——用getopt处理命令行参数(转)
    git,github在windows上的搭建
    sparc芯片验证
    睡了一下午
    UNIX/Linux里统计文件里某个字符出现的次数(转)
    linux和单片机的串口通信
  • 原文地址:https://www.cnblogs.com/xuqw/p/11794606.html
Copyright © 2011-2022 走看看