0

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

http://www.someapp.com/{Page}/{Item}

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

  1. 在浏览器中,复制 + 粘贴http://www.someapp.com/Inventory/1 //
    有效 SetParametersAsync(触发)
    b. OnSetParameters(触发)
  2. 接下来,将 URL 更改 为http://www.someapp.com/Inventory/2 //不起作用
    SetParametersAsync (未触发)
    b. OnSetParameters (未触发)

如果 {Page} 相同,即使路由参数更改,组件的生命周期也不会启动。是什么赋予了?有办法强制吗?

环境:VS2019
.NET CORE:v3.1

4

3 回答 3

0

这是一些代码(基于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-createPage 对象。这就是为什么像 OnInitialized[Async) 对这样的生命周期方法只在组件诞生时运行一次。

于 2021-04-14T10:48:01.663 回答
0

作为@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;
    }
}
于 2021-04-14T13:21:34.743 回答
0

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

它确实有助于让代码“有效”(已发布)并在我的系统上尝试以帮助定位这个时间接收器的来源。

于 2021-04-14T20:29:59.463 回答