在提供其道具/属性之前,我看不到呈现LitElement WebComponent的正确原因。如果模板需要道具,则必须在第一个无用组件之后再次渲染组件。更糟糕的是,如果您的组件看起来像这样:
class MyComp extends LitElement
static get properties() {
return {
myBigProp: {
type: Object
}
render() {
return html`<p> ${this.myBigProp.nestedProp}</p>`
}
当nestedProp
为myBigProp
时,访问undefined
时出错。是否有一种干净的方法来避免两次渲染此组件?
答案 0 :(得分:0)
如果您已经能够设置属性,则只需在构造函数中定义它们。然后应该可以在第一个渲染器上访问它。
constructor() {
super();
this.myBigProp = {nestedProp:'nested value'}
}
但是,如果您必须等待它们,我通常会通过使用“初始化”属性然后在render函数中对其进行处理来明确表明组件正在以可视方式加载。
render() {
if (!this.initialized) {
return html`<div class='loading-reserved-zone'></div>`;
} else {
return html`<p>${this.myBigProp.nestedProp}</p>`
}
}
否则,“可选链接运算符”将在2020年8月问世,它可以处理您的第二种情况,或者如果您想更早使用它,可以从技术上使用this babel plugin。
答案 1 :(得分:0)
有一个生命周期回调shouldUpdate。返回false
,直到要渲染组件。
shouldUpdate(changedProps) {
return this.myBigProp != null;
}