Blazor 表单提交需要点击两次刷新视图

Blazor form submit needs two clicks to refresh view

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

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

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 的 return JSON 数据。它永远不会在第一次点击时更新 table。我也试过在调用该方法之前将 weatherData 设置为 null 但这也不起作用。

有什么建议吗?

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

通常,组件在其事件被触发后 re-rendered;也就是说,不需要手动调用 StateHasChanged() 方法来 re-render 组件。它由 Blazor 自动调用。但在这种情况下,您确实需要手动添加 StateHasChanged() 方法才能 re-render 组件。因此你的代码应该是这样的:

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();
    }

"submit" 事件是 Blazor 中唯一一个他的操作默认被 Blazor 阻止的事件。 "submit" 事件并不真正 post 表单到服务器。请参阅:https://github.com/aspnet/AspNetCore/blob/master/src/Components/Browser.JS/src/Rendering/BrowserRenderer.ts。所以在我看来...,这只是猜测,Blazor 区别对待,并没有调用 StateHasChanged 方法来刷新组件。

此处需要调用 StateHasChanged() 的原因是因为您所指的 GetWeatherDataAsync() 方法是 void。所以服务器无法知道调用何时完成。因此,原始表单提交请求比天气数据填充更早完成。因此,对 StateHasChanged() 的调用将指示服务器需要重新呈现该组件并且可以正常工作。 一般来说,你应该简单地避免使用 async void(除非你知道它确实是 fire-and-forget 情况)和 return 某种类型的 Task 来代替,这将消除对显式 StateHasChanged() 调用。

下面,我只是将您的 GetWeatherDataAsync 方法更改为 return 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***");
}