Stencil笔记(4)- 组件钩子

import { Component } from '@stencil/core';

@Component({
  tag: 'my-component'
})
export class MyComponent {

  /**
   * 组件正在加载,尚未渲染呈现时触发调用。
   *
   * 这是在渲染前进行最后更新的地方。
   *
   * 只会被调用一次
   */
  componentWillLoad() {
    console.log('The component is about to be rendered');
  }

  /**
   * 组件已经加载完毕,并渲染呈现时触发调用。
   *
   * 在这个钩子里改变数据可能会导致组件重渲染。
   *
   *  只会被调用一次
   */
  componentDidLoad() {
    console.log('The component has been rendered');
  }

  /**
   * 当组件正在更新并重新渲染时触发调用。
   *
   * 可以多次调用,只要组件有更新。
   */
  componentWillUpdate() {
    console.log('The component will update');
  }

  /**
   * 当组件更新完毕时触发
   *
   * 调用于componentWillUpdate之后
   *
   *也是可以多次调用,只要组件有更新。
   */
  componentDidUpdate() {
    console.log('The component did update');
  }

  /**
   * 组件出栈,将被销毁时调用,用于清尾工作。
   */
  componentDidUnload() {
    console.log('The view has been removed from the DOM');
  }
}

下面是一个简单的时间显示例子:

import { Component, State } from '@stencil/core';


@Component({
  tag: 'custom-timer'
})
export class CustomTimer {

  timer: number;

  @State() time: number = Date.now();

  componentDidLoad() {
    this.timer = window.setInterval(() => {
      this.time = Date.now();
    }, 1000);
  }

  componentDidUnload() {
    clearInterval(this.timer);
  }

  render() {
    let time = new Date(this.time).toLocaleTimeString();

    return (
      <span>{ time }</span>
    );
  }
}

componentDidLoad只被调用了一次,每一秒中将现在的时间赋给time属性,time属性是用State装饰器装饰的属性,上面说到,State装饰的属性每次变化都会触发render函数,而render函数中将时间显示出来。

当组件出栈时触发componentDidUnload(),做清尾工作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值