你好,我使用的是一些类型记录的反应形式,如
this.formControls.propertyType.valueChanges.subscribe((value: string) => {
if (!this.currentSelectedType) {
this.currentSelectedType = value;
} else {
if (this.currentSelectedType === CbcPropertyType.Other) {
this.openModal();
this.currentSelectedType = value;
} else {
this.currentSelectedType = value;
}
}
});这部分代码有更好的解决方案吗,谢谢
发布于 2022-04-11 08:52:26
Jeff将这种结构称为Arrow代码,并在他的博客文章“压扁箭头码”中对其进行了描述。
可以通过添加retrun语句来避免嵌套结构,如:
this.formControls.propertyType.valueChanges.subscribe((value: string) => {
if (!this.currentSelectedType) {
this.currentSelectedType = value;
return;
}
if (this.currentSelectedType === CbcPropertyType.Other) {
this.openModal();
this.currentSelectedType = value;
return;
}
this.currentSelectedType = value;
});当我们仔细观察时,我们可以看到,这三个分支几乎是一样的。只有当currentSelectedType等于CbcPropertyType.Other时,模态才会打开。
我们可以将代码简化为:
this.formControls.propertyType.valueChanges.subscribe((value: string) => {
if (this.currentSelectedType === CbcPropertyType.Other) {
this.openModal();
}
this.currentSelectedType = value;
});
```https://codereview.stackexchange.com/questions/275679
复制相似问题