reactjs - 拉姆达或不拉姆达
问题描述
在团队中,我们试图决定是否应该ramda
在我们的项目中使用。该项目在 Typesctipt 上,前面是 React,后面是 Nestjs。
目前,优缺点列表如下所示
优点:
- 代码很容易阅读
- 纯函数易于测试和重构
缺点:
- 如果您是 ramda 新手,很难阅读
- Ramda 的类型有问题,例如
interface Obj {p1: {p2: number}}
const obj: Obj = {
p1: {
p2: 1,
}
}
const value = pathOr(null, ['p1', 'p2'], obj); //type of "value" will be "any"
- 与类一起使用
ramda
看起来很尴尬,例如
class Cl {
method1() {...}
method2() {...}
method3() {
return compose(
this.method1.bind(this),
this.method2.bind(this),
)()
}
}
很高兴看到对这些要点的任何考虑,或者添加更多的利弊。谢谢。
更新:
考虑到 geoffrey 的评论,当不可能不使用类时(比如在 NestJS 中),最好将 fp 样式的函数从类方法中分离出来,因为它们无论如何都是纯函数:
const method1Fn = () => {...};
const method2Fn = () => {...};
const method3Fn = () => compose(
method1Fn,
method2Fn,
)
class Cl {
method3() {
return method3Fn()
}
}
甚至
class Cl {
method3 = method3Fn
}
但在这种情况下,将为Cl
.
解决方案
在这种情况下,可读性是使用问题。只要您将 Ramda 的用法保持在易于使用可读的地方,就不会成为问题。
此答案中的示例
这是非常可读的:
const siblings = me => reject(equals(me), family(me));
虽然这会过度使用 Ramda,并且可读性较差(并且可能需要手动类型):
const siblings = converge(reject, [unary(equals), family])
Ramda 的类型有问题,例如
虽然你可以安装@types/ramda
推断是部分的。您可能会发现自己手动添加类型:
interface Obj {
p1: { p2: number };
}
const obj: Obj = {
p1: {
p2: 1
}
};
const fn: (obj: Obj) => null | number = pathOr(null, ['p1', 'p2']);
const value = fn(obj);
console.log(value);
将 ramda 与类一起使用看起来很尴尬,例如
您可以使用带有箭头函数的类属性来绑定方法,因此这实际上不是问题:
class Cl {
method1 = () => {...}
method2 = () => {...}
method3() {
return compose(
this.method1,
this.method2,
)()
}
}
推荐阅读
- javascript - 找不到模块“html-webpack-plguin”反应启动
- typescript - 错误:找不到模块“C:\XXX\XXX/config-overrides”
- vb.net - 如何在 vb.net 中使用 If .eof OR .bof 条件?
- alibaba-cloud - 如何从 ECS 实例中获取实例 ID?
- java - 如何使用不同的选择器直接从访问的元素中获取 XPATH
- windows - 恢复损坏的文件
- javascript - 动态创建的 div 上的 moment.js 会产生问题。最后一个时间线替换了所有其他以前的 div
- java - ConcurrentHashMap 中的 size() 和 mappingCount() 有什么区别?
- angular - 单击任何卡片时,在卡片的网格布局中插入额外的 div
- regex - notepad ++正则表达式查找和替换仅获取单词的最后一个字母而不是整个组