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组件生命周期的流程图整理图:

  • 相关阅读:
    Table交替行变色 鼠标经过变色 单击变色
    编程专用字体(雅黑字体+Consolas)
    Enterprise Architect学习笔记-EA中关系
    通用分页存储过程
    解决vs2008无法切换设计视图
    盒子模式
    ASP.NET界面数据绑定大大杂烩
    Tyvj P1032 Begin2 Unit1 身份验证
    NOIP2010普及组T1
    TyvjBegin P1036 Begin2 Unit1 数独验证
  • 原文地址:https://www.cnblogs.com/xuqw/p/11794606.html
Copyright © 2011-2022 走看看