【问题标题】:Deleting code duplication in JavaScript删除 JavaScript 中的重复代码
【发布时间】:2017-01-11 19:16:06
【问题描述】:

我注意到我的很多代码都是重复的,纯粹是因为我不知道如何在考虑变量的情况下以不同的方式重构它。

这是我的反应渲染方法中的代码:

          if (card.suit == 'D' || card.suit == 'H'){
            return <div className="cardFormatDH" key={ index }> {card.rankKey}{card.suit} </div>;
          }
          else if (card.suit == 'C' || card.suit == 'S'){
            return <div className="cardFormatCS" key={ index }> {card.rankKey}{card.suit} </div>;
          }

实际上我想说的是:

无论是d/h还是c/s都返回完全相同的东西,只是让c/s有相同的风格,d/h有相同的风格。 我的 if 条件也很长,但我想不出办法缩短它

【问题讨论】:

  • 这个问题可能更好地表述为“在 JSX 中删除代码重复”,因为这种东西在普通 JavaScript 中是微不足道的,但是对于 JSX 的所有怪异,你是对的,它不是很明显!
  • JSX 乍一看很奇怪,但这就是奇怪的地方。就像语法糖一样,它是 extraordinarily simple,这在 JSX 中并不比在 JavaScript 中小。

标签: javascript reactjs refactoring code-duplication


【解决方案1】:

您可以创建一个suit -&gt; className 地图:

const cls = {
  D: 'DH',
  H: 'DH',
  C: 'CS',
  S: 'CS',
};

并在表中查找西装,使用该值作为类名的一部分:

if (cls[card.suit]) {
  return <div className={`cardFormat${cls[card.suit]}`} key={ index }> {card.rankKey}{card.suit} </div>;
}

【讨论】:

  • 应该是cardFormat${cls[card.suit]}
【解决方案2】:

你可以写一个getCardClassname函数:

function getCardClassname(suit) {
  if (card.suit == 'D' || card.suit == 'H'){
    return "cardFormatDH";
  }
  else if (card.suit == 'C' || card.suit == 'S'){
    return "cardFormatCS";
  }
}

return <div className={getCardClassname(card.suit)} key={ index }> {card.rankKey}{card.suit} </div>;

【讨论】:

    【解决方案3】:
      // you can add more pairs here 
      const formats = [ ['D', 'H'], ['C', 'S'] ]; 
    
      for(let format of formats) {
        if(format.includes(card.suit)) {
          return (
            <div className=`cardFormat${format.join('')}` key={ index }> 
              {card.rankKey}{card.suit} 
            </div>
          );
        }
      } 
    

    【讨论】:

      猜你喜欢
      • 2011-10-07
      • 2011-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-19
      • 1970-01-01
      相关资源
      最近更新 更多