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

Jas*_*SFT 3 webassembly blazor

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

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

获取数据.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***");
    }
}
Run Code Online (Sandbox Code Playgroud)

WeatherFormModel.cs

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

        public bool IsCelcius { get; set; }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

有什么建议?

Art*_*tak 10

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

下面,我只是将您的GetWeatherDataAsync方法更改为 returnTask而不是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***");
}
Run Code Online (Sandbox Code Playgroud)


Isa*_*aac 5

当您点击“提交”按钮时,将调用 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();
    }
Run Code Online (Sandbox Code Playgroud)

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