0

我有一个简单的组件,假设它列出了一些来自 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,我在这里缺少什么吗?

4

2 回答 2

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

     StateHasChanged();
 }

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

于 2020-11-13T12:36:42.250 回答
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();});
        }
    }
}
于 2020-11-13T13:22:57.493 回答