【问题标题】:how to make the if else code better, React js如何使 if else 代码更好,React js
【发布时间】:2019-10-08 19:43:16
【问题描述】:

我想让 if else 代码变得可重用或使用开关,我该如何使用开关?

这是我的代码:

handleChange = (selectedkey) => {
    this.setState({ activeKey: selectedkey })
    if (selectedkey === '1') {
      this.updateTabNotPay();
    } else if (selectedkey === '2') {
      this.updateTabNotSent();
    } else if (selectedkey === '3') {
      this.updateTabInDelivery();
    } else if (selectedkey === '4') {
      this.updateTabFinish();
    } else if (selectedkey === '5') {
      this.updateTabCancel();
    }
  };

【问题讨论】:

  • 您是否查看过有关如何在 JavaScript 中编写 switch 语句的文档?
  • 怎么用,能不能用我上面的代码举个例子

标签: javascript reactjs


【解决方案1】:

我会避免使用switch,而是使用由selectedkey 索引的对象,其值是关联的函数名称:

const keyFnNames = {
  '1': 'updateTabNotPay',
  '2': 'updateTabNotSent',
  '3': 'updateTabInDelivery',
  '4': 'updateTabFinish',
  '5': 'updateTabCancel'
};

// ...

handleChange = (selectedkey) => {
  this.setState({ activeKey: selectedkey })
  const fnName = keyFnNames[selectedKey];
  if (fnName) {
    this[fnName]();
  }
};

如果你知道selectedKey 总会有一个对应的函数,那么你可以去掉if (fnName) 的检查。

使用switch 会不必要地冗长且更容易出错,IMO。

【讨论】:

  • 我想问一下,这个[]的作用是什么,比如这个[....]
  • 这是括号表示法,它允许您通过变量访问属性名称,例如foo = 'prop'; obj[foo]访问obj.prop
【解决方案2】:

我想这样的东西可以工作吗?

    handleChange = (selectkey) => {
this.state({ activeKey: selectedkey })
switch(selectedkey){
case 1:
this.updateTabNotPay();
break;
case 2:
this.updateTabNotSent();
break;
case 3:
this.updateTabInDelivery();
break;
case 4:
this.updateTabFinish();
break;
case 5:
this.updateTabCancel();
break;
default:
console.log("error");
}
}

强文本

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    相关资源
    最近更新 更多