web前端精简代码

react

  1. 如果onRewardClick方法存在则执行onRewardClick方法

    const {onRewardClick} = this.props
    onRewardClick && onRewardClick();
    如果props有该属性则调用这个方法不然则不调用

  2. 解构时如果该属性不存在则附一个初值

    const { liveInfo = {} } = this.props;

  3. 如果一个多次调用的属性重复使用则用一个变量进行赋值,下面反例
    在这里插入图片描述
    4 下面多个判断条件精简

if(a===1|| a===2 || a===3){
    
    
}

// 精简下面为

if([1,2,3].includes(a)){
    
    
}

5 if else精简

const a = true
if(a){
    
    
console.log(true)
}else{
    
    
console.log(false)
}
// 精简下面为

a ? console.log(true): console.log(false)
  1. switch条件精简
    我们可以将条件保存在键值对象中,并根据条件来调用它们。

// Longhand
switch (data) {
case 1:
test1();
break;
case 2:
test2();
break;
case 3:
test();
break;
// And so on…
}
// Shorthand
var data = {
1: test1,
2: test2,
3: test
};
data[something] && data[something]

猜你喜欢

转载自blog.csdn.net/qq_26889291/article/details/120347117