Blazor组件重复渲染问题求助:页面内容先渲染后消失再重现
解决Blazor页面两次渲染的问题
问题原因
你使用的@rendermode InteractiveAuto渲染模式会触发两次完整的组件生命周期:
- 首先执行服务器端静态渲染(SSR):组件在服务器初始化,调用
OnInitializedAsync获取数据并渲染页面,随后将静态HTML发送给客户端。 - 客户端启动交互式运行时后,会重新初始化组件,再次调用
OnInitializedAsync获取数据,导致第二次渲染,最终出现“产品先显示、随后消失重渲染”的现象。
解决方案
方案1:切换到单一交互式渲染模式
如果不需要服务器端静态渲染,直接将渲染模式改为InteractiveWebAssembly(纯客户端交互式)或InteractiveServer(服务器交互式),这样组件只会初始化一次:
@rendermode InteractiveWebAssembly
方案2:保留InteractiveAuto,通过状态传递避免重复获取数据
使用PersistComponentState将服务器端获取的数据传递给客户端,避免客户端再次调用API。修改代码如下:
@page "/browse" @using Design_A_Bear.Services @using Design_A_Bear.Models @using Design_A_Bear.Client.Pages.components @inject IItemService ItemService @inject PersistComponentState PersistComponentState @rendermode InteractiveAuto <PageTitle>Browse Products</PageTitle> <h3 class="fw-bold mt-4 fs-1">Browse Products</h3> @if(items.Count != 0) { <div class="d-flex mt-5"> @foreach (var item in items) { <div class="col-2" @key="item.Id"> <ItemCard Item="@item" /> </div> } </div> } else { <p>加载中...</p> } @code { List<Item> items = new List<Item>(); private const string ItemsStateKey = "BrowsePage_Items"; protected override async Task OnInitializedAsync() { // 尝试读取服务器端保存的状态数据 if (PersistComponentState.TryTakeFromJson<List<Item>>(ItemsStateKey, out var persistedItems)) { items = persistedItems; return; } // 无缓存数据时,调用服务获取 items = await ItemService.GetAllItems(); // 将数据保存到组件状态,传递给客户端 PersistComponentState.PersistAsJson(ItemsStateKey, items); } }
方案3:添加加载状态优化用户体验
如果必须保留两次渲染的流程,添加加载状态提示,避免视觉上的突兀感:
@if(items.Count != 0) { <div class="d-flex mt-5"> @foreach (var item in items) { <div class="col-2" @key="item.Id"> <ItemCard Item="@item" /> </div> } </div> } else { <div class="text-center mt-5"> <span class="spinner-border" role="status"></span> <p class="mt-2">加载产品中...</p> </div> }
内容的提问来源于stack exchange,提问作者Mat
相关产品推荐
相关产品推荐

