Blazor输入事件触发时搜索结果不更新问题及解决
Blazor输入框键盘事件触发后UI不更新问题解决
需求目标
实现用户在搜索框输入时自动更新搜索结果列表。
问题现象
触发InputText的@onkeyup事件时,搜索逻辑已正常执行,但HTML未重新渲染。即使跳过防抖处理,问题依然存在;但通过按钮的onclick事件触发搜索时,UI可正常更新。
示例代码
@using DebounceThrottle; @using System.Text.Json; @using System.Text; @inject IHttpClientFactory ClientFactory <div> <InputText @bind-Value=@searchText @onkeyup=OnInputChanged></InputText> <ul> @foreach(var result in searchResults) { <li>@result</li> } </ul> </div> @code { private DebounceDispatcher debounceDispatcher = new(1000); private string searchText = ""; private List<string> searchResults = new(); private bool shouldRender; protected override bool ShouldRender() => shouldRender; private void OnInputChanged() { debounceDispatcher.DebounceAsync(async () => { await HandleSearchRequest(); }); } private async Task HandleSearchRequest() { var request = new HttpRequestMessage(HttpMethod.Get, $"https://localhost:7284/api/search?query={searchText}"); var client = ClientFactory.CreateClient(); var response = await client.SendAsync(request); searchResults = await response.Content.ReadFromJsonAsync<List<string>>(); shouldRender = true; } }
解决方案
在防抖委托调用处添加返回语句,即可触发UI更新:
private void OnInputChanged() { return debounceDispatcher.DebounceAsync(async () => { await HandleSearchRequest(); }); }
内容的提问来源于stack exchange,提问作者wknight
相关产品推荐
相关产品推荐

