以前在写一个 React 项目时,我发现我用了太多的 if else
,因而在重构代码的时候,我尝试删除了大量的 if else
,最终发现代码变简洁了,可读性更高了。因此若是你的代码中也出现了大量的if else
,说明你的代码出问题了。javascript
在 code reviews 的时候,我会关注下面几个问题:前端
if else
,看是否能够替换它。if else
(我最喜欢用对象映射模式)。if else
,那么删除 else
,保留 if
,并返回默认值。接下来我会举几个例子来展现如何替代 if else
。java
else
重构前:react
if (red) {
return false;
} else if (blue) {
return false;
} else {
return true;
}
复制代码
重构后:后端
if (red || blue) {
return false;
}
return true;
复制代码
重构后的代码能够很直观的看到默认返回值,更简洁易读。设计模式
当你发现一个函数作了不少件事情,那么用组合函数能够很好的处理它。把函数分离成多个函数,而后把它们组合起来。app
举个例子:咱们来建立一个能够生成包含皮毛和爪子的雌性动物的函数函数
import { flow } from 'lodash';
const femaleAnimalsWithFurAndClaws = flow(
getFemales,
getAnimalsWithFur,
getAnimalsWithClaws,
)(animals);
复制代码
代码处理成这样,咱们能够很轻松的重用里面的函数(好比 getFemales)。编码
这是我最喜欢的设计模式之一,可以使用的场景也不少,无论是在前端仍是后端编码中均可以用。它带来的好处就是,让代码简洁易读。每次我用这种设计模式的时候,我都以为个人代码不是代码,而是说明书(^_^)。spa
来看一个简单的例子:
const colors = {
red: false,
blue: false,
'default': true,
};
const colorMapper = color => colors[color] || colors['default'];
const color = colorMapper(item.color);
复制代码
它由两个部分组成,一个储存返回结果的对象和一个映射函数。
咱们设置了默认值,即便在调用 colorMapper 函数的时候,没有传入参数,或者传入了错误参数,都不会报错,并返回默认值。后期维护的时候,咱们也能够很轻松的新增其余的颜色。
固然咱们也能够用 switch
来达到一样的效果,就我我的而言并不喜欢这种语法,仍是对象映射的方式更简洁优美(^_^)。
用 React 写项目,才是对象映射模式大放异彩的时候。当咱们渲染不少不一样的组件时,咱们须要在代码中写大量的条件判断。若是用对象映射模式,问题就变得简单了。看下面的例子:
首先数据看起来是这样的,每一个对象都有一个 type
和 content
键。
const items = [{
type: ‘hero’,
content: : {…},
}, {
type: 'text',
content: : {…},
}, {
type: 'image_and_text',
content: : {…},
}, {
type: 'text',
content: : {…},
}, {
type: 'call_to_action',
content: : {…},
}];
复制代码
而后写一个映射函数,每一个键表示一个 React 组件,每一个组件都有 prop
,就上面数据中的 content
。
const components = {
hero: HeroComponent,
text: TextComponent,
image_and_text: ImageAndTextComponent,
call_to_action: CallToActionComponent,
'default': null,
};
const componentMapper = type =>
components[type] || components['default'];
复制代码
接下来就能够在项目中用了:
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> ) }; 复制代码