我正在更改 Lit Web 組件的屬性,但更改后的值不會呈現。
我有一個觀察到的陣列:reports[],它將填充在 firstUpdated() 中,其中包含從 rest api 獲取的報告 url。陣列的加載通過以下方式完成:
this.reports.push({ "name" : report.Name, "url" : this.apiUrl "/" report.Name "?rs:embed=true" });
見下文:
import { LitElement, html, css } from 'lit';
import {apiUrl, restApiUrl} from '../../config';
export default class Homepage extends LitElement {
static properties = {
apiUrl: '',
restApiUrl: '',
reports: []
}
...
constructor() {
super();
this.apiUrl = apiUrl;
this.restApiUrl= restApiUrl;
this.reports = [];
}
firstUpdated() {
...
// Fetch all reports from restApiUrl:
rsAPIDetails(restApiUrl).then(reports =>{
for(const report of reports.value)
{
rsAPIDetails(restApiUrl "(" report.Id ")/Policies").then(policies => {
for(const policy of policies.Policies)
{
if(policy.GroupUserName.endsWith(usernamePBI))
{
for(const role of policy.Roles)
{
if(role != null && (role.Name== "Browser" || role.Name== "Content Manager"))
{
// User has access to this report so i'll push it to the list of reports that will show in the navbar:
this.reports.push({ "name" : report.Name, "url" : this.apiUrl "/" report.Name "?rs:embed=true" });
}
}
}
}
});
}
}).then(q => {
console.log(this.reports);
});
}
render() {
return html`
<div id="sidenav" >
...
<div >Dashboards</div>
${this.reports.map((report) =>
html`<a @click=${() => this.handleMenuItemClick(report.url)}>${report.name}</a>`
)}
<div >Options</div>
</div>
`;
}
在控制臺,我可以清楚地看到陣列加載了正確的值。但是 render() 函式不會使用 reports[] 的新值更新 web 組件: 鏈接應該添加到“儀表板”div
相反,如果我用值(在建構式中)靜態填充報告 [],它會很好地呈現鏈接。
那么為什么當觀察到的陣列改變時組件沒有更新?
謝謝!
uj5u.com熱心網友回復:
Array.push 會改變陣列,但不會改變記憶體中的實際值。
要讓 LitElement 跟蹤對陣列和物件的更新,對值的更新需要是不可變的。
例如,我們可以通過以下方式使您的示例作業:
const newReports = this.reports.slice();
newReports.push({ "name" : report.Name, "url" : this.apiUrl "/" report.Name "?rs:embed=true" });
this.reports = newReports;
或者通過使用陣列傳播
this.reports = [...this.reports, { "name" : report.Name, "url" : this.apiUrl "/" report.Name "?rs:embed=true" }]
這樣做的原因是,當你這樣做時this.reports.push(),你實際上并沒有改變 的“參考” this.reports,你只是向它添加了一個物件。另一方面,當您使用 重新定義屬性時this.reports = ...,您正在更改“參考”,因此 LitElement 知道該值已更改,并且會觸發重新渲染。
對于物件也是如此。假設您有一個財產obj。如果您僅通過向其添加屬性來更新物件,則該元素不會重新呈現。
this.obj.newProp = 'value';
但是如果通過復制物件并添加屬性的方式將物件屬性重新定義為一個整體,則會導致元素正確更新。
this.obj = {...this.obj, newProp: 'value'}
您可以使用更新的方法查看正在跟蹤和更新的值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/385693.html
上一篇:如何將asp.net的printeventargs物件傳遞給javascript
下一篇:如何從文本小部件中洗掉大括號
