• stenciljs 学习三 组件生命周期


    stenciljs 组件包含好多生命周期方法, will did load update unload
    实现生命周期的方法比价简单类似 componentWillLoad 。。。。,使用typescript
    比较方便,实现接口就可以了

    参考实现

    import { Component, Prop,ComponentDidLoad,ComponentDidUnload,ComponentWillLoad,ComponentWillUpdate } from '@stencil/core';
    
    @Component({
      tag: 'my-component',
      styleUrl: 'my-component.css',
      shadow: false
    })
    export class MyComponent implements ComponentDidLoad ,ComponentDidUnload,ComponentWillLoad,ComponentWillUpdate{
    
      @Prop() first: string;
      @Prop() last: string;
       componentWillLoad(){
         console.log("Component will to be rendered")
       }
      componentDidLoad() {
        console.log('Component has been rendered');
      }
      componentWillUpdate() {
        console.log('Component will update and re-render');
      }
      componentDidUpdate() {
        console.log('Component did update');
      }
      componentDidUnload() {
        console.log('Component removed from the DOM');
      }
    
      render() {
        return (
          <div >
            Hello, World! I'm {this.first} {this.last}
          </div>
        );
      }
    }
    

    状态渲染

    推荐的做法是任何状态的更新在 componentWillLoad() 或者 componentWillUpdate()方法中
    这些方法是在render 之前调用的,可选的是使用componentDidLoad()或componentDidUpdate()
    方法更新状态将导致另一次重新渲染,对于性能来说不是很好。
    如果必须更新状态componentDidUpdate(),则可能会使组件陷入无限循环。如果更新状态componentDidUpdate()
    是不可避免的,那么该方法还应该有一种方法来检测道具或状态是否“脏”(数据实际上是不同的还是与以前相同)。
    通过执行脏检查,componentDidUpdate()可以避免呈现相同的数据,然后componentDidUpdate()再次调用。

    生命周期的层次结构

    基本原则就是最深的组件首先完成加载,然后componentDidLoad()冒泡调用。
    参考组件

     <cmp-a>
        <cmp-b>
          <cmp-c></cmp-c>
        </cmp-b>
      </cmp-a>

    渲染顺序

    1. cmp-a - componentWillLoad()
    2. cmp-b - componentWillLoad()
    3. cmp-c - componentWillLoad()
    4. cmp-c - componentDidLoad()
    5. cmp-b - componentDidLoad()
    6. cmp-a - componentDidLoad()

    异步生命周期方法

    生命周期方法还可以返回promises,允许方法异步检索数据或执行任何异步任务

    参考:
    componentWillLoad() {
      return fetch('/some-data.json')
        .then(response => response.json())
        .then(data => {
          this.content = data;
        });
    }

    说明

    componentDidLoad 只调用一次

    参考资料

    https://stenciljs.com/docs/component-lifecycle

  • 相关阅读:
    bzoj4563: [Haoi2016]放棋子(错排+高精)
    bzoj1089 [SCOI2003]严格n元树(dp+高精)
    9.15NOIP模拟题
    洛谷 P2010 回文日期 题解
    洛谷 P1147 连续自然数和 题解
    洛谷 P1152 欢乐的跳 题解
    信息学奥赛一本通 高手训练1 统计方案数
    想学习找不到好的博客?看这里>>
    信息学奥赛一本通 高手训练1 游戏通关
    洛谷 P3398 仓鼠找sugar 题解
  • 原文地址:https://www.cnblogs.com/rongfengliang/p/9709877.html
Copyright © 2020-2023  润新知