Razor组件LocationChanged事件处理器内值无法更新问题
问题根源
Navigation.LocationChanged的事件回调是在Blazor的UI同步上下文之外执行的,就算更新了Module和Function的值,组件也不会自动触发重新渲染,所以UI上看不到变化。
修复方案
在更新完属性后手动调用StateHasChanged(),通知组件状态更新,强制刷新UI。另外别忘了在组件销毁时取消事件订阅,避免内存泄漏。
修改后的完整代码:
@inject NavigationManager Navigation @implements IDisposable <nav aria-label="breadcrumb"> <ol class="breadcrumb bg-transparent mb-0 pb-0 pt-1 px-0 me-sm-6 me-5"> @if (string.IsNullOrEmpty(Module) && string.IsNullOrEmpty(Function)) { <li class="breadcrumb-item text-sm text-dark active"><i class="fa fa-home text-primary"></i> Dashboard</li> }else if (!string.IsNullOrEmpty(Module) && string.IsNullOrEmpty(Function)) { <li class="breadcrumb-item text-sm"><a class="opacity-5 text-dark" href="/"><i class="fa fa-home text-primary"></i> Dashboard</a></li> <li class="breadcrumb-item text-sm text-dark active" aria-content="page">@Module.Humanize()</li> } else if (!string.IsNullOrEmpty(Module) && !string.IsNullOrEmpty(Function)) { <li class="breadcrumb-item text-sm"><a class="opacity-5 text-dark" href="/"> <i class="fa fa-home text-primary"></i> Dashboard</a></li> <li class="breadcrumb-item text-sm"><a class="opacity-5 text-dark" href="/@Module">@Module.Humanize()</a></li> <li class="breadcrumb-item text-sm text-dark active" aria-current="page">@Function.Humanize()</li> } </ol> </nav> @code { protected string? Module{ get; set; } protected string? Function{ get; set; } protected override void OnInitialized() { Navigation.LocationChanged += OnLocationChanged; // 首次加载时初始化面包屑 ChangeLink(); } private void OnLocationChanged(object? sender, LocationChangedEventArgs e) { ChangeLink(); // 手动通知组件刷新UI StateHasChanged(); } protected void ChangeLink() { var Parameters = Navigation.ToBaseRelativePath(Navigation.Uri).Split('/'); if (Parameters.Length > 1) { Module = Parameters[0]; Function = Parameters[1]; } else if (Parameters.Length > 0 && !string.IsNullOrWhiteSpace(Parameters[0])) { Module = Parameters[0]; Function = string.Empty; } else { Module = string.Empty; Function = string.Empty; } } // 组件销毁时取消事件订阅,防止内存泄漏 public void Dispose() { Navigation.LocationChanged -= OnLocationChanged; } }
额外优化说明
- 实现
IDisposable接口:避免组件销毁后事件订阅依然存在,引发内存泄漏 - 初始化时调用
ChangeLink():确保页面首次加载时面包屑就显示正确内容 - 增加空字符串判断:处理路径分割后出现空元素的情况,避免无效的面包屑项
内容的提问来源于stack exchange,提问作者habib
相关产品推荐
相关产品推荐

