コンポーネントのライフサイクル関数
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()
Called every time the component is disconnected from the DOM. This can happen more than once: moving an element disconnects it and connects it again.
この lifecycleフックは、Custom Elements Specで説明されているものと同じセマンティクスに従います。
Use it to undo what connectedCallback() set up. This clock starts a timer when it's added to the DOM, and stops it when it's removed:
import { Component, State } 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>
);
}
}
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 one or more of a component's Prop or State properties change and a rerender is about to be requested. It receives a single changes argument — a map of every prop/state name that changed since the last render to its { newVal, oldVal } — and should return a boolean to indicate if the component should rerender (true) or not (false).
This method is not executed before the initial render (when the component is first attached to the DOM). It fires once per render cycle, even if multiple props change synchronously:
component.somePropA = 42;
component.somePropB = 88;
Both changes are batched into a single call:
componentShouldUpdate(changes) {
if (changes['somePropA'] && changes['somePropA'].newVal === changes['somePropA'].oldVal) {
return false;
}
}
For stricter per-prop typing, use the ComponentShouldUpdateChanges<this> type:
import { ComponentShouldUpdateChanges } from '@stencil/core';
componentShouldUpdate(changes: ComponentShouldUpdateChanges<this>) {
if (changes['somePropA']?.newVal === changes['somePropA']?.oldVal) {
return false;
}
}
The per-prop (newVal, oldVal, propName) signature from versions before Stencil v5 is no longer supported. Declaring componentShouldUpdate with more than one parameter raises a compiler warning, and the extra parameters are undefined at runtime.
componentShouldUpdate() only decides whether a render goes ahead. It doesn't see changes made before the first render, so to react to a prop or state change, use @Watch().
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>