メインコンテンツまでスキップ
バージョン: v4.40

コンポーネントのライフサイクル関数

Stencilには、コンポーネントがいつロード、更新、およびレンダリングされるかを知るために使用できる多数のライフサイクルメソッドがあります。これらのメソッドをコンポーネントに追加して、適切なタイミングで操作にフックすることができます。

コンポーネントクラス内で、次に紹介するメソッドを使用すると、Stencilはそれらを正しい順序で自動的に呼び出します。

connectedCallback()​

コンポーネントがDOMに接続されるたびに、呼び出されます。 コンポーネントが最初に接続されたとき、このメソッドは componentWillLoadの前に呼び出されます。

It's important to note that this method can be called more than once, every time, the element is attached or moved in the DOM. For logic that needs to run every time the element is attached or moved in the DOM, it is considered a best practice to use this lifecycle method.

const el = document.createElement('my-cmp');
document.body.appendChild(el);
// connectedCallback() called
// componentWillLoad() called (first time)

el.remove();
// disconnectedCallback()

document.body.appendChild(el);
// connectedCallback() called again, but `componentWillLoad()` is not.

この lifecycleフックは、Custom Elements Specで説明されているものと、同じセマンティクスに従います。

disconnectedCallback()​

コンポーネントが、DOMから切断されるたびに呼び出されます。つまり、コンポーネントが複数回ディスパッチされる可能性があり、"onDestroy"のイベントと混同しないでください。

この lifecycleフックは、Custom Elements Specで説明されているものと同じセマンティクスに従います。

componentWillLoad()​

Called once just after the component is first connected to the DOM. Since this method is only called once, it's a good place to load data asynchronously and to setup the state without triggering extra re-renders.

A promise can be returned, that can be used to wait for the first render().

componentDidLoad()​

Called once just after the component is fully loaded and the first render() occurs.

componentShouldUpdate()​

This hook is called when a component's Prop or State property changes and a rerender is about to be requested. This hook receives three arguments: the new value, the old value and the name of the changed state. It should return a boolean to indicate if the component should rerender (true) or not (false).

このフックは、コンポーネントの Propまたは Stateプロパティが変更され、再レンダリングが要求されようとしているときに呼び出されます。このフックは、新しい値、古い値、および変更された状態の名前の3つの引数を受け取ります。コンポーネントを再レンダリングする必要があるか(true)、再レンダリングしないか( false)を示すブール値を返す必要があります。

Let’s say the following two props of a component change synchronously:

component.somePropA = 42;
component.somePropB = 88;

The componentShouldUpdate will be first called with arguments: 42, undefined and somePropA. If it does return true, the hook will not be called again since the rerender is already scheduled to happen. Instead, if the first hook returned false, then componentShouldUpdate will be called again with 88, undefined and somePropB as arguments, triggered by the component.somePropB = 88 mutation.

Since the execution of this hook might be conditioned, it's not good to rely on it to watch for prop changes, instead use the @Watch decorator for that.

componentWillRender()​

すべての render()の前に呼び出されます。

promiseを返すことができ、今後のレンダリングを待機するために使用できます。

componentDidRender()​

すべての render()の後に呼び出されます。

componentWillUpdate()​

一部の Prop()または State()が変更されたために、コンポーネントが更新されようとしているときに呼び出されます。 最初の render()の間に呼び出されることはありません。

promiseを返すことができ、次のレンダリングを待つために使用できます。

componentDidUpdate()​

コンポーネントが更新された直後に呼び出されます。 最初の render()の間に呼び出されることはありません。

Rendering State​

レンダリングされた状態を更新する場合は、常に componentWillLoad() または componentWillUpdate() メソッド内で行うことをお勧めします。また、 componentDidLoad()メソッドや、 componentDidUpdate()メソッド、およびcomponentDidRender()を使用してレンダリングされた状態を更新すると、別の再レンダリングが発生しますが、これはパフォーマンスにとって理想的ではありません。

componentDidUpdate()またはcomponentDidRender()で状態を更新する必要がある場合、コンポーネントが無限ループに陥る可能性があります。 もし、componentDidUpdate() 内で状態を更新することが避けられないなら、そのメソッドは、propsや状態が「ダーティ」であるかどうか(データが実際に違うのか、以前と同じなのか)を検出する方法を持っていなければいません。ダーティーチェックを行うことで、 componentDidUpdate()は同じデータをレンダリングすることを回避できます。

ライフサイクルヒエラルキー​

ライフサイクルメソッドの便利な機能は、子コンポーネントのライフサイクルも考慮に入れていることです。たとえば、親コンポーネントのcmp-aに子コンポーネントのcmp-bがある場合、cmp-aはcmp-bのロードが完了するまでロードされた"とは見なされません。別の言い方をすれば、最も深いコンポーネントが最初にロードを終えてから、 componentDidLoad()の呼び出しが始まるということです。

It's also important to note that even though Stencil can lazy-load components, and has asynchronous rendering, the lifecycle methods are still called in the correct order. So while the top-level component could have already been loaded, all of its lifecycle methods are still called in the correct order, which means it'll wait for a child components to finish loading. The same goes for the exact opposite, where the child components may already be ready while the parent isn't.

以下の例では、コンポーネントの単純な階層構造を示しています。番号付きリストは、ライフサイクルメソッドが起動する順番を示します。

  <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()

一部のコンポーネントがすでにロードされている場合とされていない場合でも、コンポーネント階層全体が子コンポーネントのロードとレンダリングを完了するのを待ちます。

非同期ライフサイクルメソッド​

Some lifecycle methods, e.g. componentWillRender, componentWillLoad and componentWillUpdate, can also return promises which allows the method to asynchronously retrieve data or perform any async tasks. A great example of this is fetching data to be rendered in a component. For example, this very site you're reading first fetches content data before rendering. But because fetch() is async, it's important that componentWillLoad() returns a Promise to ensure its parent component isn't considered "loaded" until all of its content has rendered.

以下の例は、 componentWillLoad()が親コンポーネントに、データの読み込みが完了するのを待つ方法を示す簡単な例です。

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

例​

この簡単な例は、時計を示しており、1秒ごとに現在の時刻を更新します。 componentDidLoadは1回しか呼び出さないので、タイマーのインスタンスは一度しか実行されないことになります。コンポーネントがアンロードされると、タイマーが停止します。

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

@Component({
tag: 'custom-clock'
})
export class CustomClock {

timer: number;

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

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

disconnectedCallback() {
window.clearInterval(this.timer);
}

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

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