如何尽量避免不必要的if...else...

原文链接:If… Else, or not!

简化条件判断

1
2
3
4
5
6
7
if (red) {
return true;
} else if (blue) {
return true;
} else {
return false;
}

可将代码重构为:

1
2
3
4
if (red || blue) {
return true;
}
return false;

ObjectMapper

这种做法是原文作者最爱的一种模式之一,适用于不同的场景,不管是后端还是前端项目。而且最重要的是这种做法让代码看起来非常简单,可读性也强。最基本的表现形式:

1
2
3
4
5
6
7
const colors = {
red: true,
blue: true,
'default': false,
};
const colorMapper = color => colors[color] || colors['default'];
const color = colorMapper(item.color);

ObjectMapper在React中的应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// props
const items = [{
type: ‘hero’,
content: : {…},
}, {
type: 'text',
content: : {…},
}, {
type: 'image_and_text',
content: : {…},
}, {
type: 'text',
content: : {…},
}, {
type: 'call_to_action',
content: : {…},
}];
1
2
3
4
5
6
7
8
9
10
// 将所有组件存在对象中,对象key值为props的type值
const components = {
hero: HeroComponent,
text: TextComponent,
image_and_text: ImageAndTextComponent,
call_to_action: CallToActionComponent,
'default': null,
};
const componentMapper = type =>
components[type] || components['default'];
1
2
3
4
5
6
7
8
9
10
11
12
import react from ‘react’;
const RenderItems = props => {
const componentList = props.items((item, index) => {
const Component = componentMapper(item.type);
return <Component content={item.content} />
};
return (
<div>
{componentList}
</div>
)
};