Blazor Server组件属性状态丢失:如何保留OnInitializedAsync二次调用状态?
Blazor Server ServerPrerendered模式下OnInitializedAsync状态保留示例
默认情况下,ServerPrerendered模式会执行两次组件初始化:第一次是预渲染生成静态HTML,第二次是建立SignalR连接后创建交互式组件实例。普通字段不会自动保留状态,需要使用Blazor的组件状态持久化机制来实现。
以下是可直接运行的精准代码,展示第二次OnInitializedAsync调用时属性值被保留的效果:
@page "/counter" @rendermode InteractiveServerPrerendered @inject IPersistentComponentStateStore StateStore <h1>Counter</h1> <p>当前计数: @currentCount</p> <p>OnInitializedAsync 执行次数: @initCount</p> <button class="btn btn-primary" @onclick="IncrementCount">点击增加</button> @code { private int currentCount = 0; private int initCount = 0; private const string CountStorageKey = "Counter_CurrentValue"; protected override async Task OnInitializedAsync() { initCount++; // 尝试从持久化存储中恢复之前保存的状态 if (StateStore.TryGetPersistedState<int>(CountStorageKey, out var storedCount)) { currentCount = storedCount.Value; } else { // 模拟预渲染阶段的异步初始化逻辑(比如从接口拉取数据) await Task.Delay(100); currentCount = 5; // 预渲染时设置的初始值 // 将状态持久化,供第二次初始化使用 StateStore.PersistAsJson(CountStorageKey, currentCount); } } private void IncrementCount() { currentCount++; } }
代码核心逻辑说明
- 渲染模式指定:通过
@rendermode InteractiveServerPrerendered启用预渲染+交互式Server模式 - 状态持久化依赖:注入
IPersistentComponentStateStore,这是Blazor内置的状态持久化服务 - 第一次初始化(预渲染):
- 无持久化状态,执行异步初始化逻辑并设置初始值
- 调用
PersistAsJson将状态保存到持久化存储
- 第二次初始化(交互式实例):
- 从
StateStore中读取之前保存的状态,恢复currentCount的值
- 从
运行效果
页面加载完成后,会显示:
- 当前计数: 5
- OnInitializedAsync 执行次数: 2
这证明第二次调用OnInitializedAsync时,currentCount的状态被成功保留,没有回到默认值0。
内容的提问来源于stack exchange,提问作者Ticu Ionut
相关产品推荐
相关产品推荐

