Stencil Notes (4) - Component Hooks

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');
  }
}

Here is a simple time display example:

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 is called only once, and assigns the current time to the time attribute in every second. The time attribute is an attribute decorated with the State decorator. As mentioned above, each change of the State decorated attribute will trigger the render function, and the render function The time will be displayed.

When the component is popped off the stack, componentDidUnload() is triggered to do the cleanup work.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324482386&siteId=291194637