[英]LitElement doesn't update child component from parent component
I don't understand the concept of reactivity in lit<\/code> 's web components architecture.
我不明白
lit<\/code>的 Web 组件架构中的反应性概念。
From other frameworks I come up with the assumption that the following example would update without problem, but it doesn't work with
lit<\/code> .
从其他框架中,我提出以下示例可以毫无问题地更新的假设,但它不适用于
lit<\/code> 。
I can see that the child components
render<\/code> method is only being called initially and not again after I click the button.
我可以看到子组件
render<\/code>方法仅在最初被调用,而不是在我单击按钮后再次被调用。
But even if I call it manually via the
Web Components DevTools<\/code> , it doesn't re-render with the new state.
但即使我通过
Web Components DevTools<\/code>手动调用它,它也不会以新状态重新呈现。
What do I have to change to make it work?我必须改变什么才能让它工作?
Parent component:父组件:
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>
`;
}
}
LitElement's property system only observes changes to the reference. LitElement 的属性系统只观察引用的变化。 Recursively listening for changes to child properties would be prohibitively expensive, especially for large nested objects.递归监听子属性的变化会非常昂贵,尤其是对于大型嵌套对象。
Therefore, setting a child or grandchild property of this.planetsParent<\/code> will not trigger a render.
因此,设置
this.planetsParent<\/code>的子或孙属性不会触发渲染。
So what can we do if we need to update a nested child?那么如果我们需要更新一个嵌套的孩子怎么办呢? Immutable data patterns can help us.不可变数据模式可以帮助我们。
addPlanet() {
const [...rest] = this.planetsParent;
const newItem = 'Pluto';
this.planetsParent = [newItem, ...rest];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.