【问题标题】:Blazor: data binding requires additional trigger eventsBlazor:数据绑定需要额外的触发事件
【发布时间】:2020-07-20 14:45:30
【问题描述】:

用户界面部分

<div class="input-group mb-3">
    <div class="input-group-prepend">
        <label class="input-group-text" for="inputGroupSelect">AppId</label>
    </div>
    <select class="custom-select" id="inputGroupSelect" @bind="@appId">
        @if (appIds != null)
        {
            foreach (var appId in appIds)
            {
                <option value="@appId">@appId</option>
            }
        }
    </select>
</div>
<div class="input-group mb-3">
    <div class="input-group-prepend">
        <label class="input-group-text" for="appKeyFormControlInput">AppKey</label>
    </div>
    <input type="text" class="form-control" id="appKeyFormControlInput" @bind="@appKey" @bind:event="oninput">
    <div class="input-group-append">
        <button class="btn btn-outline-secondary" type="button" @onclick="SetAppKey">Get AppKey</button>
    </div>
</div>

代码部分

@code
{
    private IEnumerable<string> appIds;

    private string appId { get; set; }
    private string appKey { get; set; }

    protected override async Task OnInitializedAsync()
    {
        using HttpClient httpClient = new HttpClient();
        var result = await httpClient.GetAsync("API_ADDR");
        appIds = JObject.Parse(await result.Content.ReadAsStringAsync())["content"].ToObject<IEnumerable<string>>();
        appId = appIds?.FirstOrDefault();
    }

    private async void SetAppKey()
    {
        using HttpClient httpClient = new HttpClient();
        var result = await (await httpClient.GetAsync("API_ADDR")).Content.ReadAsStringAsync();
        if (!string.IsNullOrWhiteSpace(result))
        {
            var app = JObject.Parse(result)["content"].ToObject<Application>();
            appKey = app.AppKey;
        }
    }
}

期待

当我点击获取 AppKey 按钮时,
input#appKeyFromControlInput 的值显示
当前AppId的appkey(input#inputGroupSelect)。

其实:

当我点击Get AppKey按钮时,
input#appKeyFromControlInput没有反应;
当我再次点击 Get AppKey 时,
input#appKeyFromControlInput 显示正确的 appkey。

环境

  1. .NET 5 预览版 6
  2. Blazor WebAssembly
  3. Windows 10 2004

【问题讨论】:

    标签: .net-core blazor


    【解决方案1】:

    以下代码"

    <label class="input-group-text" for="appKeyFormControlInput">AppKey</label>
    

    应该是

    <label class="input-group-text" for="appKeyFormControlInput">@AppKey</label>
    

    AppKey 被编译器解释为一个字符串,而@AppKey 被认为是一个应该被计算的表达式,其结果将显示在开始和结束标记之间。

    你也应该改变这个:private async void SetAppKey()

    对此:private async Task SetAppKey()

    当您使用 async void 时,您的方法不会返回已完成的 Task 对象,因此周围没有人知道您的组件何时应该重新渲染。因此,您的组件不会在第一次单击时呈现,仅在第二次单击时呈现,反映第一次单击的值。

    始终将 async 与 Task 一起使用,而不是与 void 一起使用。

    注意:点击事件等 UI 事件总是会触发组件的重新渲染。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-02
      • 2012-11-17
      • 2020-01-31
      • 2020-02-27
      • 2014-07-02
      • 2014-06-24
      • 2013-07-31
      • 1970-01-01
      相关资源
      最近更新 更多