首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >简单的价值重构--类型转换

简单的价值重构--类型转换
EN

Code Review用户
提问于 2022-04-11 06:54:07
回答 1查看 53关注 0票数 0

你好,我使用的是一些类型记录的反应形式,如

代码语言:javascript
运行
复制
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;
    }
  }
});

这部分代码有更好的解决方案吗,谢谢

EN

回答 1

Code Review用户

发布于 2022-04-11 08:52:26

Jeff将这种结构称为Arrow代码,并在他的博客文章“压扁箭头码”中对其进行了描述。

可以通过添加retrun语句来避免嵌套结构,如:

代码语言:javascript
运行
复制
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时,模态才会打开。

我们可以将代码简化为:

代码语言:javascript
运行
复制
this.formControls.propertyType.valueChanges.subscribe((value: string) => {
  if (this.currentSelectedType === CbcPropertyType.Other) {
    this.openModal();
  }

  this.currentSelectedType = value;
});
```
代码语言:javascript
运行
复制
票数 2
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/275679

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档