Blazor交互式服务器端Razor页面_persons列表点击搜索后闪烁问题
Blazor InteractiveServer模式下搜索结果闪烁问题解决
问题根源不是垃圾回收,而是表单默认提交行为导致页面刷新。你的Search按钮放在<form>标签内,点击按钮时浏览器会触发表单的默认提交动作,导致整个页面重新加载,刚渲染出来的列表会随着页面刷新而消失,看起来就是“一闪而过”。
解决方案
有两种简单的解决方式:
方式1:阻止按钮的默认提交行为
给Search按钮添加@onclick:preventDefault属性,阻止浏览器的默认表单提交:
<button class="btn-primary" @onclick="Search" @onclick:preventDefault>Search</button>
方式2:移除不必要的form标签
如果这个区域不需要表单提交功能,直接把<form class="form-control">换成<div class="form-control">:
<div class="form-control"> <button class="btn-primary" @onclick="Search">Search</button> </div>
修改后的完整代码示例
@page "/" @using BlazorPorter.Models @using BlazorPorter.Context @using Microsoft.EntityFrameworkCore @inject SqliteContext SqliteContext @rendermode InteractiveServer <PageTitle>Home</PageTitle> <form class="form-control"> <input placeholder="id" @bind="_id"/> <input placeholder="name" @bind="_name"/> <button class="btn-primary" @onclick="@Insert" @onclick:preventDefault>Insert</button> </form> <div class="form-control"> <button class="btn-primary" @onclick="Search">Search</button> </div> @if (_persons != null) { @foreach (Person p in _persons) { <p>@p.Id</p> <p>@p.Name</p> } } @code { private string? _id; private string? _name; private List<Person>? _persons; private async Task Insert() { if (_id != null && _name != null) { await SqliteContext.AddAsync(new Person() { Id = _id, Name = _name }); await SqliteContext.SaveChangesAsync(); } } private void Search() { if (SqliteContext.Persons != null) { _persons = SqliteContext.Persons.ToList(); } } }
注:Insert按钮也建议添加@onclick:preventDefault,避免误触表单提交。
内容的提问来源于stack exchange,提问作者BoomBoom
相关产品推荐
相关产品推荐

