这是在改进园子 vscode 插件时遇到的一个问题,下面的 PostCate 类型有个 children 属性,不知什么原因会造成 children 的值被置空,从而造成 tree view 的数据绑定出现问题
export class PostCateStore {
constructor(private categories: PostCate[]) { }
}
export class PostCate {
children?: PostCat[] | null
}
排查半天没找到根源,现在想把这个数组设置为 immutable 即只读状态,以避免数组元素的值被修改
typescript 中有个现成的 ReadonlyArray
export class PostCateStore {
constructor(private categories: ReadonlyArray<PostCate>) { }
}
改用 ReadonlyArray 之后,立马通过编译错误就发现了问题所在,是下面的代码中 const queue = this.categories
引起的问题
getChildren(categoryId: number) {
if (this.isNullOrEmpty) return []
let children: PostCate[] = []
const queue = this.categories
while (queue.length > 0) {
const current = queue.pop()
if (current == null) continue
if (current.categoryId === categoryId) {
if (current.children != null) children = current.children
break
}
if (current.children != null) for (const child of current.children) queue.unshift(child)
}
children = PostCateeStore.clonePostCate(children)
return children
}
改为调用 getRoots
方法从 this.categories
clone 根节点解决了
const queue = this.getRoots()
typescript有个Readonly关键字可以试试
type TItem = {
name: string
children?: Readonly<TItem[]>
}
还有readonly和ReadonlyArray,可以根据需求选择使用
@彼时今日: ReadonlyArray
是正解