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

  • 相关阅读:
    阿里云oss大文件切片上传
    轻量全景查看器 pannellum初探
    基于.NetCore开发博客项目 StarBlog (15) 生成随机尺寸图片
    GitLab的安装、配置、使用
    Django数据库性能优化之 使用Python集合操作
    合阔智云核心生产系统切换到服务网格 ASM 的落地实践
    应用发布新版本如何保障流量无损
    传统 Web 框架部署与迁移
    云原生可观测套件:构建无处不在的可观测基础设施
    鱼传科技:函数计算,只要用上就会觉得香
  • 原文地址:https://www.cnblogs.com/xuqw/p/11794606.html
Copyright © 2020-2023  润新知