【问题标题】:Blazor: Forcing Component/Page Life-cycleBlazor:强制组件/页面生命周期
【发布时间】:2021-04-14 04:59:15
【问题描述】:
【问题讨论】:
标签:
routes
blazor
lifecycle
blazor-webassembly
route-parameters
【解决方案1】:
这里有一些代码(基于 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++;
}
}
注意:由于 Blazor reuses 页面(当前为计数器)具有不同的参数;也就是说,它没有re-create Page 对象。这就是为什么像 OnInitialized[Async) 对这样的生命周期方法只在组件诞生时运行一次。
【解决方案2】:
作为@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;
}
}
【解决方案3】:
我会尝试删除这个问题,但我的问题的解决方案是缓存策略。硬重新加载后,页面将按预期运行。感谢那些花时间帮助解决这个问题的人。
它确实有助于让代码“有效”(已发布)并在我的系统上尝试以帮助定位这个时间汇的来源。