LWC: Lifecycle Hooks

1. constructor()
它在component被创建时调用。
This hook flows from parent to child,即它首先在parent中触发。
使用constructor()须知:
  1. Constructor中的第一个语句必须是super(). 设置之后this.才会有效
  2. 在constructor中不要使用return语句。除非是要做一个提前返回(return或return this)
  3. 不可以使用document.write()或document.open()方法
  4. 不可以检查elements
  5. 不可以检查properties. Properties是在constriction之后,connectedCallback之前分配给component的。

2. connectedCallback()
connectedCallback()是在component实例化lifecycle的特定阶段触发的callback method. 当component插入DOM时,connectedCallback() lifecycle hook就会被触发。
This hook flows from parent to child.
我们可以在connectedCallback()中给properties赋值,调用apex method,触发一个custom event,执行一个UI Api call,使用navigation service. 但是不能在connectedCallback()中访问elements
connectedCallback()可能会被触发多次。例如,如果删除了一个element之后由将其insert到另一个位置,或者对list进行重新排序。如果希望代码只运行一次,就要编写代码以防止它运行多次。

3. renderedCallback()
它在每次render component之后被调用。当在component中直接引用的property或者在getter中间接引用的property的值发生改变时,component就会rerender
This hook flows from child to parent.
在renderedCallback()中更新component,可能会导致无限循环。例如:
  1. 不要在renderedCallback()中更新wire adapter configiuration objecgt property
  2. 不要在renderedCallback()中更新public property或者field

4. disconnectedCallback()
它在从document中删除element时被调用。
This hook flows from parent to child.
可以使用disconnectedCallback()清理掉在connectedCallback()中完成的工作,例如清除caches或者删除event listeners.

5. errorCallback(error, stack)
它在descendant component(后代组件)抛出错误时被调用。
error参数是一个JavaScript原生错误对象,stack参数是一个string.
需要注意的时error boundary仅从其children捕获错误,而不是从其本身。
所以如果想要在component中应用它,可以参考下列代码:
<!-- boundary.html -->
<template>
  <template if:true={this.error}>
    <error-view error={this.error} info={this.stack}></error-view>
  </template>
  <template if:false={this.error}>
    <healthy-view></healthy-view>
  </template>
</template>

// boundary.js
import { LightningElement } from 'lwc';
export default class Boundary extends LightningElement {
error;
stack;
  errorCallback(error, stack) {
    this.error = error;
  }
}

posted @ 2021-07-15 17:40  Clsriz  阅读(150)  评论(0编辑  收藏  举报