【发布时间】:2021-12-13 17:10:08
【问题描述】:
我已经简化了我遇到的 lit 问题。我的组件的某些状态保存在一个对象中。我希望能够通过一些精细的控制来检测子属性的变化并做出反应。示例如下:
import { html, LitElement } from "lit";
import { customElement, state } from "lit/decorators.js";
@customElement("my-app")
export class App extends LitElement {
@state({
hasChanged(newVal: any, oldVal: any) {
console.log(`[hasChanged] new fruit is: ${newVal?.fruit}`);
console.log(`[hasChanged] old fruit is: ${oldVal?.fruit}`);
return true;
}})
data = {
fruit: "apples",
weather: "rain",
};
constructor() {
super();
setTimeout(() => {
this.data.fruit = "bananas";
this.data = { ...this.data };
}, 3000);
setTimeout(() => {
this.data.weather = "snow";
this.data = { ...this.data };
}, 6000);
}
render() {
return html`
Weather: ${this.data.weather} Fruit: ${this.data.fruit}
`;
}
shouldUpdate(changedProperties: any) {
// I only want to update if the weather is changing, not the fruit
console.log(
`new weather is: ${changedProperties.get("data")?.weather}`
);
console.log(`current weather is: ${this.data.weather}`);
console.log(`new fruit is: ${changedProperties.get("data")?.fruit}`);
console.log(`current fruit is: ${this.data.fruit}`);
console.log("");
if (changedProperties.get("data")?.weather !== this.data.weather) {
return true;
} else {
return false;
}
}
}
当 shouldUpdate 触发时,组件对子属性值的评估已经更新。所以我无法将changedProperties.get("data")?.weather 与this.data.weather 进行比较,看看它是否发生了变化。
[更新] 根据 michaPau 的建议,我研究了 hasChanged 方法 - 不幸的是,当触发更改时,这也会返回相同的 oldVal 和 newVal 值。
有人知道新方法或修复方法吗?如果我将该状态对象拆分为两个单独的状态变量,它会按预期工作,但对象和属性在保持代码可读性方面效果要好得多。在我看来,将超过 4 或 5 个属性传递到组件中开始变得混乱。
【问题讨论】:
-
你试过属性
hasChanged函数吗?请参阅lit doc。 -
不,我没有看到。谢谢,我会玩它...
-
不高兴,@michaPau,请参阅我的帖子更新。
-
我会使用扩展运算符来设置新的子值:比如
this.data = {...this.data, fruit: 'orange'};,并且没有明确的this.data.fruit = ....。这应该保持旧值可用。
标签: lit