【问题标题】:Why does await InvokeAsync(StateHasChanged()); or StateHasChanged() not change anything or re-render in Blazor?为什么等待 InvokeAsync(StateHasChanged());或 StateHasChanged() 不改变任何东西或在 Blazor 中重新渲染?
【发布时间】:2022-01-07 02:41:39
【问题描述】:

我想在删除或创建新产品时刷新表格组件。 我试着打电话给await InvokeAsync(StateHasChanged());StateHasChanged()

但是 Table 组件没有刷新它的数据,我必须手动点击刷新按钮才能看到变化

    public async Task HandleValidSubmit()
    {
        ReceivedProduct = new MyBlazorApp.Models.Product();
        using (var httpClient = new HttpClient())
        {
            StringContent content = new StringContent(JsonConvert.SerializeObject(ProductData), Encoding.UTF8, "application/json");

            using (var response = await httpClient.PostAsync("https://localhost:7104/api/Products", content))
            {
                string apiResponse = await response.Content.ReadAsStringAsync();
                ReceivedProduct = JsonConvert.DeserializeObject<MyBlazorApp.Models.Product>(apiResponse);
            }
        }
        FormSubmitMessage = "Product Created";

        await InvokeAsync(StateHasChanged);
    }

    protected async Task Delete(int Id)
    {
        await client.DeleteAsync("api/products/" + Id);
        FormSubmitMessage = "Product with ID: " + Id + " is deleted.";
        
        await InvokeAsync(StateHasChanged);
    }

【问题讨论】:

标签: c# razor blazor


【解决方案1】:

在您调用 StaeHasChanged() 的两种情况下,它都是不必要的 - 它已经在您的事件处理程序之后被调用。

但是 Table 组件不会刷新它的数据,

您需要重新加载数据。大致:

protected override async Task OnInitializedAsync()
{
    await LoadTable();
} 

....

protected async Task Delete(int Id)
{
    await client.DeleteAsync("api/products/" + Id);
    FormSubmitMessage = "Product with ID: " + Id + " is deleted.";
    
    //await InvokeAsync(StateHasChanged);
    await LoadTable();
}

【讨论】:

    猜你喜欢
    • 2021-03-21
    • 2020-03-14
    • 1970-01-01
    • 2020-08-11
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 2021-01-23
    相关资源
    最近更新 更多