Blazor學習記錄_8.預呈現__

22. NET8中的預呈現

  • 預呈現是在服務器上初始呈現頁面內容的過程(無需爲呈現的控件啓用事件處理程序)。服務器會根據初始請求儘快輸出頁面的HTML UI,這會讓用戶感覺應用提高了響應速度。預呈現還可以通過呈現搜索引擎用於計算網頁排名的初始HTTP響應的內容,來改進搜索引擎優化(SEO)
    https://learn.microsoft.com/zh-cn/aspnet/core/blazor/components/prerender?view=aspnetcore-8.0
    沒有預呈現效果就是,當頁面初始化方法中要執行一些耗時任務時,整個頁面的渲染必須等待這些耗時任務執行完畢,然後才能呈現。尤其在WebAssembly項目中,前面要下載整個程序集...
    預呈現試圖過把耗時任務先暫時剝離,而嘗試先呈現能夠渲染的最初始的頁面Html和CSS,比如先呈現頁面框架,從而減少用戶等待...

22.1 代碼中開啓預呈現的方法

從組件參數設置交互模式時,如代碼:
<Perrender Title="開啓預呈現" @rendermode="new InteractiveServerRenderMode(true)">
<Perrender Title="開啓預呈現" @rendermode="new InteractiveWebAssemblyRenderMode(true)">

22.2 預呈現帶來的負面問題

  • 22.2.1 在InteractiveServerRenderMode中,寫在生命週期OnInitializedAsync()方法中的耗時任務,會在任務完成後,又渲染一次頁面。
  • 22.2.2 兩次渲染頁面,會讓第一次的頁面中的元素值或都說某些狀態被第二次渲染而覆蓋,造成狀態無法保持(比如第一次渲染產生了從隨機函數獲得了一個隨機數,第二次渲染又會獲得一次而且與第一次不同)。解決方法:Blazor爲組件專們設計了一個用來進行狀態持久化的類型 PersistentComponetState 它相當於一個單例的字典類型或者一種緩存,使用時在第一次渲染時,把第一次渲染產生的狀態保存在此,當第二次渲染時從此中取出即可。如代碼:
@page "/prerendered-counter-2"
@implements IDisposable
@inject ILogger<PrerenderedCounter2> Logger
@inject PersistentComponentState ApplicationState

<PageTitle>Prerendered Counter 2</PageTitle>
<h1>Prerendered Counter 2</h1>
<p role="status">Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount;
    private PersistingComponentStateSubscription persistingSubscription;

    protected override void OnInitialized()
    {
        persistingSubscription =
 ApplicationState.RegisterOnPersisting(PersistCount);
        if (!ApplicationState.TryTakeFromJson<int>(
            nameof(currentCount), out var restoredCount))
        {
            currentCount = Random.Shared.Next(100);
            Logger.LogInformation("currentCount set to {Count}", currentCount);
        }
        else
        {
            currentCount = restoredCount!;
            Logger.LogInformation("currentCount restored to {Count}", currentCount);
        }
    }
    private Task PersistCount()
    {
        ApplicationState.PersistAsJson(nameof(currentCount), currentCount);
        return Task.CompletedTask;
    }
    void IDisposable.Dispose() => persistingSubscription.Dispose();
    private void IncrementCount()
    {
        currentCount++;
    }
}
  • 22.2.3 如果渲染模式是在組件定義時指定的,則無法在組件使用時使用預呈現。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章