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(),做清尾工作。

猜你喜欢

转载自blog.csdn.net/qq993284758/article/details/79947337
今日推荐