【问题标题】:LitElement doesn't update child component from parent componentLitElement 不会从父组件更新子组件
【发布时间】:2021-10-05 15:33:27
【问题描述】:

我不明白lit 的 Web 组件架构中的反应性概念。从其他框架中,我假设以下示例将毫无问题地更新,但它不适用于lit

我可以看到子组件render 方法仅在最初被调用,而在我单击按钮后不再被调用。但即使我通过Web Components DevTools 手动调用它,它也不会以新状态重新渲染。

我必须改变什么才能让它工作?

父组件:

import {LitElement, html} from 'lit';
import {customElement, property} from 'lit/decorators.js';
import './show-planets';

@customElement('lit-app')
export class LitApp extends LitElement {

    addPlanet() {
        this.planetsParent.push('Pluto')
        console.log('this.planetsParent', this.planetsParent)
    }

    @property({type: Array}) planetsParent = ['Mars'];

    render() {
        return html`
            <button @click="${this.addPlanet}">click</button>
            <show-planets .planetsChild="${this.planetsParent}"></show-planets>
        `;
    }
}

子组件:

import {LitElement, html} from 'lit';
import {customElement, property} from 'lit/decorators.js';

@customElement('show-planets')
export class ShowPlanets extends LitElement {

    @property({type: Array}) planetsChild = ['Pluto'];

    render() {
        console.log('this.planetsChild', this.planetsChild);
        return html`<h1>Planets are: ${this.planetsChild}</h1>`;
    }
}

【问题讨论】:

  • 与 React 完全一样,Lit 只有在引用发生变化时才能检测到变化。推送到数组对引用没有任何作用,您需要做的是 this.planetsParent = [...this.planetsParent, 'Pluto']; 参见此处:lit.dev/docs/components/properties/#haschanged
  • 你可以像@ChrisG 提到的那样做,或者只是在addPlanet 函数中调用this.requestUpdate() 来通知lit 发生了一些变化
  • 我们有生命周期方法来执行基于监听器的各种工作。也许这可以帮助你https://lit-element.polymer-project.org/guide/lifecycle

标签: javascript typescript lit-element lit-html lit


【解决方案1】:

LitElement 的属性系统只观察引用的变化。递归侦听对子属性的更改会非常昂贵,尤其是对于大型嵌套对象。

因此,设置this.planetsParent 的子或孙属性不会触发渲染。

那么,如果我们需要更新嵌套的孩子,我们该怎么办?不可变数据模式可以帮助我们。

addPlanet() {
    const [...rest] = this.planetsParent;
    const newItem = 'Pluto';
    this.planetsParent = [newItem, ...rest];
}

参考:https://open-wc.org/guides/knowledge/lit-element/rendering/#litelement-rendering

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-20
    • 1970-01-01
    • 2019-03-11
    • 2018-02-20
    • 2019-12-04
    • 2018-04-18
    • 2020-02-14
    • 2021-02-27
    相关资源
    最近更新 更多