[英]Using component lifecycle events in Ember
根據最新的Ember文檔,不鼓勵使用觀察者,而贊成重寫組件生命周期掛鈎。 我不確定如何有效地使用這些鈎子。 該文件說,你可以使用didUpdateAttrs
和didReceiveAttrs
作為替代觀察員。
假設我有一個可以繪制一些數據的組件。 該組件看起來像:
{{my-chart data=data showLabels=showLabels otherProps=otherProps}}
設置data
,它需要對數據執行一些分析,因此只有在data
是真正的新數據時,才應執行此操作。 showLabels
屬性在圖表中顯示/隱藏標簽,並通過my-chart
之外的內容進行切換。
我選擇使用didReceiveAttrs
作為它在初始和后續渲染上運行的方式,並將其編碼為:
didReceiveAttrs() {
let data = this.getAttr('data');
this.performAnalytics(data);
let showLabels = this.get('showLabels');
this.updateHideLabels(showLabels);
}
問題在於,每次更改任何屬性時, didReceiveAttrs
中的所有代碼都會運行。 因此,如果用戶反復執行導致showLabels
更改的操作,則還會調用performAnalytics
,這很不好,因為它會導致圖表刷新。
我的具體問題是,我如何將諸如didReceiveAttrs
類的生命周期事件用作觀察者,以便僅執行已更改的屬性的代碼路徑?
我會說我嘗試存儲該屬性並將其與傳入的屬性進行比較,但是我覺得這樣效率很低,尤其是在data
是一組復雜對象的情況下。
您可以編寫一個實用程序文件,例如utils/component-lifecycle.js
。
export const attrsHaveChanged = ((changes, attr) => {
const { oldAttrs, newAttrs } = changes;
if (oldAttrs) {
const oldAttrsValue = JSON.stringify(oldAttrs[attr].value);
const newAttrsValue = JSON.stringify(newAttrs[attr].value);
return oldAttrsValue !== newAttrsValue;
} else {
return true;
}
});
現在您可以在組件中導入它,
import { attrsHaveChanged } from 'appname/utils/component-lifecycle';
並使用它
didReceiveAttrs(changes) {
if (attrsHaveChanged(changes, 'chartData')) {
doSomething();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.