MudTable/MudTablePager切换每页行数时ServerData触发两次问题
MudTable切换RowsPerPage时ServerData触发两次的问题(非第一页场景)
问题现象
- 处于非第一页时切换RowsPerPage(每页行数)选项,
ServerData绑定的ServerReload方法会触发两次 - 第一页切换行数时无此异常,仅触发一次
环境信息
- MudBlazor版本:v6.17.0
相关代码
MudTable组件代码
<MudTable @ref="@_Mudtable" ServerData="@(new Func<TableState, Task<TableData<UsuarioTela>>>(ServerReload))" Hover="true" Breakpoint="Breakpoint.Sm" Striped="true" LoadingProgressColor="Color.Info"> <HeaderContent> <MudTh></MudTh> <MudTh>Código</MudTh> <MudTh>Nome</MudTh> <MudTh>Ativo</MudTh> <MudTh></MudTh> </HeaderContent> <RowTemplate> <MudTd style="width: 50px;"> <MudIconButton Icon="@Icons.Material.Filled.DeleteForever" @onclick="@(() => Delete(context.id))" aria-label="Excluir" Color="Color.Error"></MudIconButton> </MudTd> <MudTd DataLabel="Código">@context.cod</MudTd> <MudTd DataLabel="Nome">@context.nome</MudTd> <MudTd DataLabel="Ativo">@context.descFlgAtivo</MudTd> <MudTd> <MudButton Variant="Variant.Outlined" Size="Size.Small" Color="Color.Primary">Editar</MudButton> </MudTd> </RowTemplate> <NoRecordsContent> <MudText>Nenhum registro encontrado</MudText> </NoRecordsContent> <LoadingContent> <MudText>Carregando...</MudText> </LoadingContent> <PagerContent> <MudTablePager PageSizeOptions="new int[] { 10, 25, 50, 100, 500 }" RowsPerPageString="Total de linhas:" HorizontalAlignment="HorizontalAlignment.Center" /> </PagerContent> </MudTable>
ServerReload方法实现
private async Task<TableData<UsuarioTela>> ServerReload(TableState state) { UsuarioLigacao usrL = new UsuarioLigacao(); lstUsr = await usrL.preencheLista2Async(null, null, state.Page * state.PageSize, state.PageSize); totalRows = usrL.totalLinhas; return new TableData<UsuarioTela>() { TotalItems = totalRows, Items = lstUsr }; }
问题分析与处理方案
这并非配置遗漏,而是MudBlazor v6.x版本的已知组件行为问题:非第一页切换页大小时,组件内部会先触发页码重置逻辑,再执行页大小变更操作,导致两次ServerData调用。
临时修复方案
在ServerReload方法中添加防抖逻辑,取消重复的未完成请求:
private CancellationTokenSource? _cts; private async Task<TableData<UsuarioTela>> ServerReload(TableState state) { // 取消之前未完成的请求 _cts?.Cancel(); _cts = new CancellationTokenSource(); try { UsuarioLigacao usrL = new UsuarioLigacao(); lstUsr = await usrL.preencheLista2Async(null, null, state.Page * state.PageSize, state.PageSize, cancellationToken: _cts.Token); totalRows = usrL.totalLinhas; return new TableData<UsuarioTela>() { TotalItems = totalRows, Items = lstUsr }; } catch (OperationCanceledException) { // 返回缓存数据或空列表 return new TableData<UsuarioTela>() { TotalItems = totalRows, Items = lstUsr ?? new List<UsuarioTela>() }; } finally { _cts.Dispose(); _cts = null; } }
长期解决方案
关注官方修复进度,升级到已修复该问题的MudBlazor版本。
内容的提问来源于stack exchange,提问作者Willian Lima
相关产品推荐
相关产品推荐

