Blazor:强制组件/页面生命周期



我正在使用Blazor Web程序集构建应用程序,我希望用户能够通过路由加载应用程序,例如

http://www.someapp.com/{页面}/{项目}

如果用户选择上述路线,则应转到{Page}并显示{item}
这是开箱即用的;但是,如果用户应用以下步骤:

  1. 在浏览器中,复制+粘贴http://www.someapp.com/Inventory/1//工作
    a。设置参数同步(已激发(
    b。OnSetParameters(已激发(
  2. 下一步,将URL更改为http://www.someapp.com/Inventory/2//不起作用
    a。设置参数同步(未激发(
    b。OnSetParameters(未激发(

如果{Page}相同,则即使路由参数已更改。什么东西?有办法强迫它吗?

环境:VS2019
.NET CORE:v3.1

作为@enet答案的附录。当我需要了解组件生命周期中发生了什么时,我使用以下代码块和标记:

@page "/lifecyclebar"
------  Your code
<div class="container m-2 px-3 p-t bg-dark text-white">
<div class="row">
<div class="col-3">
Initialized: @this.InitRun
</div>
<div class="col-3">
Set Params: @this.SetParamsAsync
</div>
<div class="col-3">
Params Set: @this.ParamsSet
</div>
<div class="col-3">
Rendered: @this.Rendered
</div>
</div>
</div>
@code {
---- your code
private int SetParamsAsync = 0;
private int InitRun = 0;
private int ParamsSet = 0;
private int Rendered = 1;
//  add to existing method if you have one
protected override Task OnInitializedAsync()
{
InitRun++;
return base.OnInitializedAsync();
}
//  add to existing method if you have one
protected override Task OnParametersSetAsync()
{
this.ParamsSet++;
return base.OnParametersSetAsync();
}
//  add to existing method if you have one
public override Task SetParametersAsync(ParameterView parameters)
{
this.SetParamsAsync++;
return base.SetParametersAsync(parameters);
}
//  add to existing method if you have one
protected override bool ShouldRender()
{
Rendered++;
return true;
}
}

这里有一些代码(基于Counter组件(,复制并测试它。您自己看看,当您更改参数值时,这两个方法都会执行。

顺便说一句,它是OnParametersSet,而不是

OnSetParameters(未触发(

@page "/counter/{MyCount:int}"
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
[Parameter]
public int MyCount { get; set; }
protected override void OnParametersSet()
{
Console.WriteLine("OnParametersSet");
}
public override async Task SetParametersAsync(ParameterView parameters)
{
Console.WriteLine("SetParametersAsync");
await base.SetParametersAsync(parameters);
}
private void IncrementCount()
{
currentCount++;
}
}

注:由于Blazorreuses的页面(当前计数器(具有不同的参数;也就是说,它不re-create页面对象。这就是为什么像OnInitialized[Async(对这样的生命周期方法在组件诞生时只运行一次

我会尝试删除这个问题,但解决问题的方法是缓存策略。在硬重新加载之后,页面将按预期运行。感谢那些花时间帮助解决这个问题的人。

它确实有助于代码";有效的";(发布的(,并在我的系统上尝试,以帮助定位这个时间汇的来源。

最新更新