sup*_*610 19 javascript reactjs higher-order-components
我有一个显示样式文本的React组件,我想让它加载网络资源,监听WebSocket输入和显示通知.为了做到这一点,我写的高阶组件封装功能对于每一种:withResource,withSocket,和withNotifications.
导出组件时,这是正确的吗?
class TextComponent extends React.Component {
...
}
export default withResource(withSocket(withNotifications(TextComponent)))
Run Code Online (Sandbox Code Playgroud)
mer*_*lin 40
import { compose } from 'redux'
export default compose(
withResource,
withSocket,
withNotifications
)(TextComponent)
Run Code Online (Sandbox Code Playgroud)
import { compose } from 'recompose'
export default compose(
withResource,
withSocket,
withNotifications
)(TextComponent)
Run Code Online (Sandbox Code Playgroud)
Pur*_*lex 11
它被称为函数组合,它具有数学背景(导致y和x变量命名和函数的反向执行)。它通过消除变量额外定义和深层次的函数包装来降低调用书面函数的方式的复杂性。
:由自己或使用来自就像一个图书馆写它lodash,rambda,redux,等。
const compose = (...rest) => x => rest.reduceRight((y, f) => f(y), x)
Run Code Online (Sandbox Code Playgroud)
与头等函数一起使用:
const increment = (numb) => numb + 1
const multiplyBy = (multiplyNum) => (num) => multiplyNum * num
compose(increment, multiplyBy(3), increment)(4)// 4 > 5 > 15 > 16
Run Code Online (Sandbox Code Playgroud)
与高阶组件一起使用:
compose(withRouter, withItems, withRefs)(Component)
Run Code Online (Sandbox Code Playgroud)
小智 8
另一个简单的解决方案可以通过三个步骤来完成此操作,只需将 HOC 组件放在彼此之上,如下所示:
const firstHOC = withNotifications(TextComponent);
const secondHOC = withSocket(firstHOC);
export default withResource(secondHOC);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10210 次 |
| 最近记录: |