【问题标题】:Blazor form submit needs two clicks to refresh viewBlazor 表单提交需要两次单击才能刷新视图
【发布时间】:2020-04-22 00:55:30
【问题描述】:

我有以下 Blazor 组件,我正在测试 API 调用以获取天气数据。出于某种原因,需要单击提交按钮两次才能使表格显示更新后的对象的属性。

当页面初始化时,我从浏览器中获取位置就好了,天气数据显示在表格中没有问题。

FetchData.razor

@page "/fetchdata"
@using BlazingDemo.Client.Models
@using AspNetMonsters.Blazor.Geolocation

@inject HttpClient Http
@inject LocationService LocationService

<h1>Weather forecast</h1>
<p>This component demonstrates fetching data from the server.</p>

<div>
    <EditForm Model="@weatherForm" OnValidSubmit="@GetWeatherDataAsync">
        <DataAnnotationsValidator />
        <ValidationSummary />
        <InputText Id="cityName" bind-Value="@weatherForm.CityName" />
        <button type="submit">Submit</button>
    </EditForm>
</div>
<br />

@if (weatherData == null)
{
    <Loader/>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>City</th>
                <th>Conditions</th>
                <th>Temp. (C)</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>@weatherData.Name</td>
                <td>@weatherData.Weather[0].Main</td>
                <td>@weatherData.Main.Temp</td>
            </tr>
        </tbody>
    </table>
}

@functions {

    WeatherFormModel weatherForm = new WeatherFormModel();
    WeatherData weatherData;
    Location location;

    protected override async Task OnInitAsync()
    {
        location = await LocationService.GetLocationAsync();

        if (location != null)
        {
            weatherData = await GetWeatherDataAsync(location.Latitude,location.Longitude);
        }
    }

    protected async Task<WeatherData> GetWeatherDataAsync(decimal latitude, decimal longitude)
    {
        return await Http.GetJsonAsync<WeatherData>($"https://api.openweathermap.org/data/2.5/weather?lat={location.Latitude}&lon={location.Longitude}&units=metric&appid=***removed***");
    }

    protected async void GetWeatherDataAsync()
    {
        weatherData = await Http.GetJsonAsync<WeatherData>($"https://api.openweathermap.org/data/2.5/weather?q={weatherForm.CityName}&units=metric&appid=***removed***");
    }
}

WeatherFormModel.cs

namespace BlazingDemo.Client.Models
{
    public class WeatherFormModel
    {
        [Required, Display(Name = "City Name")]
        public string CityName { get; set; }

        public bool IsCelcius { get; set; }
    }
}

我正在调用 GetWEatherDataAsync() 方法,通过检查 Chrome 的返回 JSON 数据,我可以看到每次调用时从 API 返回的数据。它只是永远不会在第一次点击时更新表格。在调用该方法之前,我也尝试将weatherData 设置为null,但这也不起作用。

有什么建议吗?

【问题讨论】:

    标签: webassembly blazor


    【解决方案1】:

    这里需要StateHasChanged() 调用的原因是因为您所指的GetWeatherDataAsync() 方法是void。因此,服务器无法知道调用何时完成。因此,原始表单提交请求在填充天气数据之前完成。因此,对StateHasChanged() 的调用将指示服务器需要重新渲染组件并且可以正常工作。 一般来说,您应该避免使用async void(除非您知道它确实是fire-and-forget 的情况),而是返回某种类型的Task,这样就无需显式调用StateHasChanged()

    下面,我只是将您的GetWeatherDataAsync 方法更改为返回Task 而不是void

    protected async Task GetWeatherDataAsync()
    {
        weatherData = await Http.GetJsonAsync<WeatherData>($"https://api.openweathermap.org/data/2.5/weather?q={weatherForm.CityName}&units=metric&appid=***removed***");
    }
    

    【讨论】:

    • 这个GitHub issue 似乎表明Blazor 支持异步事件处理程序,并且在MSDN documentation 中也提到了。这意味着这是正确的答案。
    • @Artak - 在这个例子中重构的代码看起来如何?
    • 现在将其添加到我的答案中
    【解决方案2】:

    当您点击“提交”按钮时,会调用 GetWeatherDataAsync() 方法,并将数据检索到 weatherData 变量中...并结束其任务...

    通常,组件在其事件被触发后重新渲染;即无需手动调用 StateHasChanged() 方法重新渲染组件。它由 Blazor 自动调用。但在这种情况下,您确实需要手动添加 StateHasChanged() 方法才能重新渲染组件。因此你的代码应该是这样的:

    protected async void GetWeatherDataAsync()
        {
            weatherData = await Http.GetJsonAsync<WeatherData>($"https://api.openweathermap.org/data/2.5/weather?q={weatherForm.CityName}&units=metric&appid=***removed***");
    
            StateHasChanged();
        }
    

    “提交”事件是 Blazor 中唯一一个 Blazor 默认阻止其操作的事件。 “提交”事件并没有真正将表单发布到服务器。请参阅:https://github.com/aspnet/AspNetCore/blob/master/src/Components/Browser.JS/src/Rendering/BrowserRenderer.ts。所以在我看来......,这只是一个猜测,Blazor 对待它的方式不同,并且不会调用 StateHasChanged 方法来刷新组件。

    【讨论】:

    • 哇,这应该是我们公共文档的一部分。我会提出建议的更改。干杯。
    猜你喜欢
    • 1970-01-01
    • 2013-12-28
    • 2021-10-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-27
    • 2021-03-05
    • 2014-12-03
    相关资源
    最近更新 更多