我已经习惯了Blazor WASM。我有一些页面是从自定义基类继承。在这个基类中,我有一个级联参数。
public class CustomBlazorComponentBase : LayoutComponentBase
{
private bool disposedValue;
[Inject]
protected HttpInterceptorService Interceptor { get; set; }
[CascadingParameter]
protected TelerikNotification Notification { get; set; }
protected override Task OnInitializedAsync()
{
Interceptor.RegisterEvent(Notification.ShowError);
return base.OnInitializedAsync();
}
}
在MainLayout。我有以下几行
<CascadingValue IsFixed="true" Value="@Notification">
<div class="content px-4">
@Body
</div>
</CascadingValue>
<TelerikNotification @ref="@Notification" Class="notification"
HorizontalPosition="@NotificationHorizontalPosition.Center"
VerticalPosition="@NotificationVerticalPosition.Bottom" />
页面开始
@inherits ItnBlazorComponentBase
HttpInterceptor-Class获得一个委托来显示出错。一切正常,如预期。
但是当用户不小心按下浏览器的F5键来刷新页面时,没有生命周期方法被调用。不是OnInitializedAsync,也不是OnParametersSetAsync等等。
为什么?如何避免这个问题呢?问题是,我的委托没有注册,所以没有Notification显示。
谢谢!
经过几个小时的研究,回答了我自己的问题。这个问题很简单,答案来自Stackoverflow
最外层的CascadingValue在页面刷新或直接链接时丢失
解决方案是在MainLayout中包围CascadingParameter。带有布尔值
的剃刀@if (HasRendered)
{
<CascadingValue IsFixed="true" Value="@Notification">
<div class="content px-4">
@Body
</div>
</CascadingValue>
}
在MainLayout.razor.cs后面的代码中设置它在第一次渲染后
protected override void OnAfterRender(bool firstRender)
{
if(firstRender)
{
HasRendered = true;
StateHasChanged();
}
base.OnAfterRender(firstRender);
}
我应用了您的解决方案,但问题仍未解决,刷新页面时级联参数丢失@ if (HasRendered){@Body
}
然后定义bool变量HasRendered并将下面的代码粘贴到MainLayout.razor.cs中OnAfterRender(bool firstRender){如果(firstRender){hasrender = true;StateHasChanged ();}
base.OnAfterRender(firstRender);
}