Blazor

作者 mindrally97184105b5da無授權條款269 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫5 週前更新

Guidelines for Blazor development including component lifecycle, state management, and performance optimization

AI 產生的概覽

Blazor 開發指南,涵蓋元件架構、生命週期、狀態管理、效能、測試與驗證。

功能
此技能提供 .NET 中 Blazor 應用程式開發的參考指引,同時涵蓋 Blazor Server 與 Blazor WebAssembly。內容包括元件設計與結構、生命週期方法、單向與雙向資料繫結、事件處理、轉譯最佳化與虛擬化、以階層式參數與狀態容器進行的狀態管理、HTTP API 整合、錯誤界限、bUnit 測試以及驗證模式。它提供說明文字與 Razor、C# 程式碼範例,而非指令碼或產生的檔案。
適用情境
在撰寫、審查或偵錯 Blazor 元件與頁面,且需要生命週期、繫結、轉譯或狀態方面慣例時使用。也適合在 Blazor Server 與 WebAssembly 之間做選擇、接上驗證,或建立 bUnit 元件測試時使用。
執行需求
此技能不附帶指令碼或資源,僅為指示性內容。使用這些指引需要 .NET Blazor 專案以及對 Razor 與 C# 的認識;bUnit 測試範例意味著需要 bUnit 測試程式庫,HTTP 範例則意味著需要以 HttpClient 為基礎的 API。

Blazor Development Guidelines

You are an expert in Blazor development with deep knowledge of both Blazor Server and Blazor WebAssembly.

Component Architecture

Component Design

  • Create small, focused components
  • Use component parameters for input
  • Use EventCallback for output/events
  • Implement IDisposable for cleanup
  • Use cascading parameters sparingly

Component Structure

razor
@page "/users/{Id:int}"@inject IUserService UserService
<h1>@User?.Name</h1>
@code {    [Parameter]    public int Id { get; set; }
    private User? User { get; set; }
    protected override async Task OnInitializedAsync()    {        User = await UserService.GetUserAsync(Id);    }}

Component Lifecycle

Lifecycle Methods

  • OnInitialized/OnInitializedAsync: Initial setup
  • OnParametersSet/OnParametersSetAsync: When parameters change
  • OnAfterRender/OnAfterRenderAsync: After DOM updates
  • Dispose: Cleanup resources

Best Practices

  • Use OnInitializedAsync for data loading
  • Check firstRender in OnAfterRenderAsync
  • Dispose subscriptions and timers
  • Avoid long-running synchronous code

Data Binding

One-Way Binding

razor
<p>@message</p><input value="@inputValue" />

Two-Way Binding

razor
<input @bind="inputValue" /><input @bind="inputValue" @bind:event="oninput" />

Event Handling

razor
<button @onclick="HandleClick">Click</button><button @onclick="() => HandleClickWithParam(id)">Click</button><button @onclick="HandleClickAsync">Async Click</button>

Render Optimization

Prevent Unnecessary Renders

  • Use @key for list items
  • Implement ShouldRender() when appropriate
  • Use StateHasChanged() judiciously
  • Avoid inline handlers in loops

Virtualization

razor
<Virtualize Items="@items" Context="item">    <ItemContent>        <div>@item.Name</div>    </ItemContent></Virtualize>

State Management

Component State

  • Use private fields for component state
  • Call StateHasChanged() when state changes externally
  • Use InvokeAsync for thread-safe updates

Cascading Parameters

razor
<CascadingValue Value="@currentTheme">    <ChildComponent /></CascadingValue>
<!-- In child component -->[CascadingParameter]public Theme CurrentTheme { get; set; }

State Containers

  • Create injectable state services
  • Use events for state change notifications
  • Consider Fluxor for complex state management

Blazor Server vs WebAssembly

Blazor Server

  • State lives on server
  • Real-time connection via SignalR
  • Faster initial load
  • Requires stable connection
  • Better for internal apps

Blazor WebAssembly

  • Runs entirely in browser
  • Larger initial download
  • Works offline (PWA capable)
  • No server resources per user
  • Better for public apps

API Integration

HTTP Client

csharp
@inject HttpClient Http
private async Task LoadData(){    users = await Http.GetFromJsonAsync<List<User>>("api/users");}

Error Handling

csharp
try{    users = await Http.GetFromJsonAsync<List<User>>("api/users");}catch (HttpRequestException ex){    errorMessage = "Failed to load users";}

Error Handling

Error Boundaries

razor
<ErrorBoundary>    <ChildContent>        <RiskyComponent />    </ChildContent>    <ErrorContent Context="ex">        <p>An error occurred: @ex.Message</p>    </ErrorContent></ErrorBoundary>

Global Error Handling

  • Implement IErrorBoundary for custom handling
  • Log errors to server
  • Show user-friendly messages

Testing

bUnit Testing

csharp
[Fact]public void ComponentRendersCorrectly(){    using var ctx = new TestContext();    var cut = ctx.RenderComponent<Counter>();
    cut.Find("p").MarkupMatches("<p>Current count: 0</p>");    cut.Find("button").Click();    cut.Find("p").MarkupMatches("<p>Current count: 1</p>");}

Authentication

Setup

  • Use AuthenticationStateProvider
  • Use AuthorizeView for conditional UI
  • Use [Authorize] attribute on pages
  • Implement custom auth state provider for JWT

AuthorizeView

razor
<AuthorizeView>    <Authorized>        <p>Welcome, @context.User.Identity?.Name!</p>    </Authorized>    <NotAuthorized>        <p>Please log in.</p>    </NotAuthorized></AuthorizeView>

Performance Tips

  • Use @key for dynamic lists
  • Implement virtualization for large lists
  • Lazy load components with @if
  • Minimize JavaScript interop calls
  • Use streaming rendering in .NET 8+

來源與署名

來源:mindrally/skills位於blazor提交9718410

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架