如何优化selectionManager.select()?解决批量选择时系统卡顿问题
解决selectionManager.select操作卡顿的优化方案
分批异步处理选择操作
一次性传入大量selectionId会阻塞主线程,导致页面冻结。将选择列表拆分为小批次,通过setTimeout分批执行选择操作,给浏览器留出UI渲染的时间:
const selectionList = []; indices.forEach((index: number) => { const selection = selectionIdBuilder.createSelectionIdBuilder() .withTable(dataTableOrigin, index) .createSelectionId(); selectionList.push(selection); }); // 分批处理逻辑 const batchSize = 50; // 根据数据量调整批次大小 let currentBatchIndex = 0; function processNextBatch() { const batch = selectionList.slice(currentBatchIndex, currentBatchIndex + batchSize); if (batch.length === 0) return; // 第二个参数传true,追加当前批次的选择,避免全量刷新 selectionManager.select(batch, true); currentBatchIndex += batchSize; // 让出主线程,避免阻塞 setTimeout(processNextBatch, 0); } // 最后执行一次全量选择,确保最终状态正确 setTimeout(() => { selectionManager.select(selectionList, false); }, 0); processNextBatch();
过滤已选中的重复项
如果列表中存在已被选中的项,提前过滤可以减少select方法的处理量:
const selectionList = []; indices.forEach((index: number) => { const selection = selectionIdBuilder.createSelectionIdBuilder() .withTable(dataTableOrigin, index) .createSelectionId(); selectionList.push(selection); }); // 过滤已选中的项 const selectedIds = new Set(selectionManager.getSelectionIds().map(id => id.key)); const filteredList = selectionList.filter(sel => !selectedIds.has(sel.key)); if (filteredList.length > 0) { selectionManager.select(filteredList, false); }
利用浏览器空闲时段执行操作
如果选择操作不需要立即完成,使用requestIdleCallback让浏览器在空闲时执行,避免抢占UI渲染资源:
const selectionList = []; indices.forEach((index: number) => { const selection = selectionIdBuilder.createSelectionIdBuilder() .withTable(dataTableOrigin, index) .createSelectionId(); selectionList.push(selection); }); // 浏览器空闲时执行选择操作 requestIdleCallback(() => { selectionManager.select(selectionList, false); }, { timeout: 1000 }); // 设置超时,防止等待过久
内容的提问来源于stack exchange,提问作者Ngô Sơn Tùng
相关产品推荐
相关产品推荐

