VSCode SCM扩展切换资源组视图不更新问题求助
问题分析与修复方案
核心问题点
- 资源组存储类型错误:用数组
tagResourceGroups/pathResourceGroups存储键值对(路径/标签作为键),但数组的forEach仅遍历数字索引元素,导致旧资源组无法被遍历和dispose。 - 遍历资源状态语法错误:遍历资源组内的资源状态时,未指定所属的资源组对象,且错误使用全局
forEach,导致资源状态未被正确销毁。 - 资源状态创建方式错误:错误地将字面量赋值给
vscode.SourceControlResourceState接口,这会覆盖全局接口定义,而非创建符合接口要求的资源状态对象。 - 未彻底清空旧资源组引用:dispose后未重置存储对象,残留的旧引用导致视图无法更新。
修复后的代码
const vscode = require('vscode'); const globals = require('./globals'); // 改用对象存储资源组,键为路径/标签,方便遍历和查找 let tagResourceGroups = {}; let pathResourceGroups = {}; function addResourceStateToGroup(resourceGroup, uri, status) { // 直接创建符合SourceControlResourceState接口的字面量对象,无需赋值给全局接口 const resourceState = { resourceUri: uri, command: { command: 'vscode.open', title: 'Open File', arguments: [uri] }, decorations: { tooltip: status, strikeThrough: false, faded: false } }; resourceGroup.resourceStates = [...resourceGroup.resourceStates, resourceState]; } function buildResourceGroups() { console.log('清理旧资源组...'); // 清理标签资源组:遍历所有资源组,销毁资源状态和资源组 Object.values(tagResourceGroups).forEach(rg => { rg.resourceStates.forEach(res => res.dispose()); rg.dispose(); }); tagResourceGroups = {}; // 清空对象 // 清理路径资源组 Object.values(pathResourceGroups).forEach(rg => { rg.resourceStates.forEach(res => res.dispose()); rg.dispose(); }); pathResourceGroups = {}; // 清空对象 const sortTreeMode = globals.config.sortTreeMode; console.log(`当前排序模式: ${sortTreeMode}`); console.log('构建新资源组...'); if (sortTreeMode === 'path') { pathList.forEach(path => { if (path !== undefined && path !== '') { pathResourceGroups[path] = sourceControl.createResourceGroup(path, path); pathResourceGroups[path].hideWhenEmpty = true; } }); } else if (sortTreeMode === 'tag') { tagList.forEach(tag => { if (tag !== undefined && tag !== '') { tagResourceGroups[tag] = sourceControl.createResourceGroup(tag, tag); tagResourceGroups[tag].hideWhenEmpty = true; } }); } console.log('分配资源状态...'); resourceSum.forEach(resource => { if (!resource || !resource.fullPath) return; const resourceStatus = resource.managed === '1' ? 'Unchanged' : 'Modified'; const filePath = resource.fullPath; if (sortTreeMode === 'path' && resource.scope) { const group = pathResourceGroups[resource.path]; if (group) { // 确保资源组存在 addResourceStateToGroup(group, vscode.Uri.file(filePath), resourceStatus); } } else if (sortTreeMode === 'tag' && resource.parTagName) { const group = tagResourceGroups[resource.parTagName]; if (group) { // 确保资源组存在 addResourceStateToGroup(group, vscode.Uri.file(filePath), resourceStatus); } } }); }
额外优化点
- 增加空值判断,避免因无效资源导致的报错。
- 资源组查找时增加存在性检查,防止因键不存在导致的未定义错误。
- 使用
Object.values()遍历对象的所有资源组,确保所有旧资源组都被清理。
内容的提问来源于stack exchange,提问作者GallifreyMage
相关产品推荐
相关产品推荐

