【问题标题】:Updating object in C# with data that came from JSInterop not re-rendering使用来自 JSInterop 的数据更新 C# 中的对象,而不是重新渲染
【发布时间】:2021-02-25 10:21:03
【问题描述】:

我有一个简单的组件,假设它列出了一些来自 IndexedDB 的客户,我可以很好地检索数据,甚至可以看到对象在设置一些断点时获取值,但是组件在获取后不会重新渲染数据更新。

为简单起见,Customers.razor:

@inject IJSRuntime js
@foreach(var item in Data)
{
    <h5>@item.Name</h5>
}
@code{
    protected List<CustomerModel> Data { get; set; }

    protected override  async Task OnAfterRenderAsync(bool firstRender)
    {
        Data = await js.InvokeAsync<List<CustomerModel>>("Database.get", "customers");
    }
}

在 .NET Core 3.1 上运行 Blazor,我这里有什么遗漏吗?

【问题讨论】:

    标签: blazor blazor-jsinterop


    【解决方案1】:
    @inject IJSRuntime js
    
    @* Verify that the data is not null and the list contains items, otherwise
       an exception is thrown *@ 
    @if( Data != null && Data.Any())
    {
        @foreach(var item in Data)
        {
            <h5>@item.Name</h5>
        }
    }
    
    
    @code{
        protected List<CustomerModel> Data { get; set; }
    
        protected override  async Task OnAfterRenderAsync(bool firstRender)
        {
            // Call only once 
            if( firstRender )
            {
                 Data = await js.InvokeAsync<List<CustomerModel>>("Database.get", 
                                                                 "customers");
                 InvokeAsync(() => { StateHasChanged();});
            }
        }
    }
    

    【讨论】:

    • 不需要InvokeAsync,直接调用Statehaschanged();在 firstRender 的验证中成功了,谢谢
    • 使用 InvokeAsync 是一种很好的做法,因为 Blazor 正在发展,而且在不久的将来,两种 Blazor 风格都可能使用多个线程
    【解决方案2】:
     protected override  async Task OnAfterRenderAsync(bool firstRender)
     {
         Data = await js.InvokeAsync<List<CustomerModel>>("Database.get", "customers");
    
         StateHasChanged();
     }
    

    应该可以,但可能需要InvokeAsync(StateHasChanged);

    【讨论】:

    • StateHasChanged();是缺少的部分,谢谢,但请注意,必须验证 firstRender == true 因为如果不是,则进行无限重新渲染
    猜你喜欢
    • 2018-04-04
    • 2021-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多