Chuyển đến nội dung
Skillpedia
Website và giao diện (frontend)5.8k · #14568

support-prerendering

Skill này làm gì

Skill này sửa các vấn đề xảy ra khi trang Blazor được vẽ lần đầu trên server rồi chuyển quyền điều khiển sang trình duyệt. Skill dành cho lập trình viên .NET gặp tải dữ liệu trùng lặp, nháy màn hình hoặc lỗi null khi tải trang.

Khi nào nên dùng

  • ✓Khi một trang Blazor tải cùng dữ liệu hai lần hoặc bị nháy khi tải lần đầu.
  • ✓Khi lỗi null reference xuất hiện trong bước prerendering.
  • ✓Khi bạn cần trạng thái được giữ lại từ lần render đầu tiên ở server sang trang tương tác.

Liên kết skill

https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/support-prerendering/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/support-prerendering/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Trang sản phẩm Blazor của tôi tải dữ liệu hai lần và bị nháy. Hãy sửa để nó chỉ tải một lần.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Agent đọc thiết lập tương tác của ứng dụng, bảo vệ bước prerendering, lưu trạng thái đã tải để trang tương tác dùng lại, rồi kiểm tra cách trang hoạt động khi tải.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Support Prerendering

How Prerendering Works

Prerendering is on by default for all interactive render modes. The server renders the component as static HTML and ships it to the browser immediately. Then the interactive runtime (Server/WebAssembly) loads and re-renders the component with full interactivity.

This means:

  • OnInitializedAsync runs twice — once during prerender (static), once when the interactive runtime attaches.
  • OnAfterRenderAsync is NOT called during prerender — only after the interactive render.
  • Internal navigation between interactive pages (interactive routing) skips prerendering — prerendering only happens on full page loads.

Step 1 — Read the Project's AGENTS.md

Check the project's AGENTS.md for the Interactivity Mode and Interactivity Scope:

Mode Prerendering applies?
None (Static SSR) No — there's no interactive handoff
Server Yes
WebAssembly Yes
Auto Yes

If the mode is None, this skill doesn't apply.

Persist State Across Prerender → Interactive

The most common prerendering problem: data loaded in OnInitializedAsync during prerender is thrown away and re-fetched when the interactive runtime attaches. This causes flicker and duplicate API/DB calls.

Recommended: [PersistentState] attribute

Annotate properties to automatically serialize during prerender and restore on interactive activation:

@page "/forecasts"
@rendermode InteractiveServer

<h1>Weather</h1>

@if (Forecasts is null)
{
    <p>Loading...</p>
}
else
{
    @foreach (var f in Forecasts)
    {
        <p>@f.Date: @f.TemperatureC°C</p>
    }
}

@code {
    [PersistentState]
    public WeatherForecast[]? Forecasts { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Forecasts ??= await ForecastService.GetForecastsAsync();
    }
}

The ??= pattern is critical — it means "only fetch if the property wasn't already restored from prerender state."

Multiple instances of the same component

When the same component type appears multiple times, use @key to disambiguate state:

@foreach (var item in items)
{
    <ItemCard @key="item.Id" />
}

Advanced: PersistentComponentState service

For complex scenarios (dynamic keys, custom serialization), use the imperative API:

@inject PersistentComponentState ApplicationState

@code {
    private List<Order>? orders;

    protected override async Task OnInitializedAsync()
    {
        ApplicationState.RegisterOnPersisting(PersistOrders);

        if (!ApplicationState.TryTakeFromJson<List<Order>>("orders", out var restored))
        {
            orders = await OrderService.GetOrdersAsync();
        }
        else
        {
            orders = restored;
        }
    }

    private Task PersistOrders()
    {
        ApplicationState.PersistAsJson("orders", orders);
        return Task.CompletedTask;
    }
}

Disable Prerendering

Disable prerendering when a component depends on browser APIs immediately or when the prerender+interactive double render causes problems you can't solve with [PersistentState].

On a component definition

@rendermode @(new InteractiveServerRenderMode(prerender: false))

Replace InteractiveServerRenderMode with InteractiveWebAssemblyRenderMode or InteractiveAutoRenderMode as needed.

On a component instance

<MyChart @rendermode="new InteractiveServerRenderMode(prerender: false)" />

On the entire app

In App.razor:

<HeadOutlet @rendermode="new InteractiveServerRenderMode(prerender: false)" />
<Routes @rendermode="new InteractiveServerRenderMode(prerender: false)" />

Note: A parent's prerendering setting overrides children. If <Routes> disables prerendering, individual pages cannot re-enable it.

Exclude Pages from Interactive Routing

In a globally interactive app, some pages may need HttpContext (cookies, request headers, response status codes). These pages must render via static SSR, not inside the interactive runtime.

Use [ExcludeFromInteractiveRouting]:

@page "/privacy"
@attribute [ExcludeFromInteractiveRouting]

<h1>Privacy Policy</h1>

This forces a full page reload when navigating to this page, exiting interactive routing. The page renders as static SSR with full HttpContext access.

In App.razor, conditionally apply the render mode:

<!DOCTYPE html>
<html>
<
Câu hỏi thường gặp

Prerendering là gì?

Đó là việc server vẽ trang dưới dạng HTML tĩnh trước, để trang hiện ra nhanh trước khi tương tác bắt đầu.

Skill có áp dụng cho trang tĩnh không?

Không. Nếu ứng dụng không dùng chế độ tương tác nào, sẽ không có bước chuyển giao cần sửa.

Có thể tắt prerendering không?

Có. Skill bao quát việc tắt prerendering hoặc loại trừ các trang khỏi định tuyến tương tác.

Chi tiết

Mô tả gốc của tác giả

Make interactive Blazor components work correctly with prerendering. USE FOR fixing duplicate data loads, UI flicker during prerender-to-interactive handoff, null references during prerender, persisting state across prerender, disabling prerendering, excluding pages from interactive routing, or detecting whether a component is currently prerendering. DO NOT USE for choosing which render mode to use (see create-blazor-project) or general component authoring (see author-component).

repo: dotnet/skills

Độ phổ biến

Sao GitHub
5.8k
Vị trí xếp hạng
#14568
Giấy phép
MIT
Cập nhật
2/11/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự