Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net core 数据驱动组件的Blazor渲染优化_Asp.net Core_Blazor_Blazor Server Side - Fatal编程技术网

Asp.net core 数据驱动组件的Blazor渲染优化

Asp.net core 数据驱动组件的Blazor渲染优化,asp.net-core,blazor,blazor-server-side,Asp.net Core,Blazor,Blazor Server Side,我一直在思考如何优化典型数据驱动Blazor组件的渲染。考虑下面的简化组件(部分): 公共部分类FooComponent:ComponentBase { [注入] 受保护的IBarService BarService{get;set;} [参数] 公共字符串OptionalParameter1{get;set;} [参数] 公共字符串OptionalParameter2{get;set;}; 受保护的IEnumerable项{get;set;} 受保护的覆盖任务OnParametersSetAs

我一直在思考如何优化典型数据驱动Blazor组件的渲染。考虑下面的简化组件(部分):

公共部分类FooComponent:ComponentBase
{
[注入]
受保护的IBarService BarService{get;set;}
[参数]
公共字符串OptionalParameter1{get;set;}
[参数]
公共字符串OptionalParameter2{get;set;};
受保护的IEnumerable项{get;set;}
受保护的覆盖任务OnParametersSetAsync()
{
this.Items=等待this.BarService.GetItemsAsync(this.OptionalParameter1,this.OptionalParameter2);
}
}
该组件有两个可选参数。它们通常可以是服务调用的一些筛选值。组件无法知道父组件是否会设置这些参数(因为它们是可选的)。只要设置了参数,组件就会通过(昂贵的)异步服务调用检索
BarItem
项的列表。然后,组件标记以某种方式呈现
列表

问题是每次设置参数时都会调用
OnParametersSetAsync
,导致组件重新渲染并执行另一个服务调用。我可以通过检查参数值是否已更改来部分优化它,但仍然会有多个服务调用

  • 如果从未设置这两个参数,则服务调用只发生一次(良好)
  • 如果设置了一个参数,服务调用将发生两次(第一次使用错误的参数值)
  • 如果两个参数都设置了,服务调用将发生3次(前2次参数值错误)
在具有更多属性的真实组件中,这可能会很快导致许多不需要的服务调用。如果对所有参数调用一次
OnParametersSetAsync
,这将不是一个问题(我知道Blazor不是这样工作的)


我能做些什么来确保服务调用在参数值正确的情况下只发生一次?在我看来,这似乎是数据驱动组件中非常常见的场景,如果无法(有效地)实现,这将是Blazor的一个真正缺点。

昨天在dotnet Conf Focus Blazor中,Daniel Roth展示了类似的情况。 要解决此问题,可以使用计时器,该计时器在每次设置一个参数时启动。如果计时器达到时间限制,则调用搜索请求。 这叫做去盎司


如果可以的话,我将尝试为演示挖掘github repo。

使用OnInitializedAsyncinstead@aguafrommars参数尚未在OnInitializedAsync上设置,仅在OnAfterRenderAsync上调用onceSorry
OnAfterRenderAsync
OnAfterRender也无法工作,因为组件已渲染,因此检索数据为时已晚
public partial class FooComponent: ComponentBase
{
    [Inject]
    protected IBarService BarService { get; set; }

    [Parameter]
    public string OptionalParameter1 { get; set; }

    [Parameter] 
    public string OptionalParameter2 { get; set; };

    protected IEnumerable<BarItem> Items { get; set; }

    protected override Task OnParametersSetAsync()
    {
        this.Items = await this.BarService.GetItemsAsync(this.OptionalParameter1, this.OptionalParameter2);
    }
}