Blazor 8 Sections:如何更新MainLayout中的SectionOutlet?
解决Blazor 8 Sections跨布局更新不生效的问题
问题原因
你的MainLayout大概率使用的是静态渲染模式(Blazor Web App默认全局布局通常为静态),静态组件仅在初始加载时渲染一次,无法响应后续InteractiveServer页面中SectionContent的状态更新。而页面内的本地SectionOutlet属于同一交互式上下文,因此能正常同步数值。
解决方案
将MainLayout切换为交互式渲染模式,让它能接收SectionContent的状态变更通知:
- 在
MainLayout.razor顶部添加渲染模式指令:
@rendermode InteractiveServer
若要全局配置,也可在App.razor中指定布局的渲染模式:
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" LayoutRenderMode="InteractiveServer" />
- 确认页面中
SectionContent与布局的SectionOutlet名称匹配:
<!-- /changedata页面示例代码 --> <SectionContent SectionName="s-test"> 当前计数:@_clickCounter </SectionContent> <SectionContent SectionName="s-test-local"> 本地计数:@_clickCounter </SectionContent> <button @onclick="IncrementCount">点击增加</button> @code { private int _clickCounter; private void IncrementCount() { _clickCounter++; } }
补充说明
Sections功能确实可替代部分CascadingValues/EventCallbacks的使用场景,但前提是提供SectionContent的组件与接收SectionOutlet的组件处于同一交互式渲染上下文,或接收方为可响应状态变更的交互式组件。静态布局无法感知交互式页面内的状态变化,因此只会显示初始值。
内容的提问来源于stack exchange,提问作者Dave_B.
相关产品推荐
相关产品推荐

