I have a React component that displays styled text, and I want to have it load a network resource, listen for WebSocket input, and display notifications. In order to do this, I write Higher Order Component wrapper functions for each of these: withResource
, withSocket
, and withNotifications
.
When exporting the component, is this correct?
class TextComponent extends React.Component {
...
}
export default withResource(withSocket(withNotifications(TextComponent)))
答案 0 :(得分:30)
You can use compose
from redux or recompose. For example:
import { compose } from 'redux'
export default compose(
withResource,
withSocket,
withNotifications
)(TextComponent)
import { compose } from 'recompose'
export default compose(
withResource,
withSocket,
withNotifications
)(TextComponent)
答案 1 :(得分:2)
它被称为功能组合,它具有数学背景(导致 y 和 x 变量命名和功能的反向执行)。通过消除变量的额外定义和深度的函数包装,可以降低调用书面函数的方式的复杂性。
您可以自行编写,也可以在TextInputEditText
,lodash
,rambda
等库中使用。
redux
与一流的功能一起使用:
const compose = (...rest) => x => rest.reduceRight((y, f) => f(y), x)
与高阶组件一起使用:
const increment = (numb) => numb + 1
const multiplyBy = (multiplyNum) => (num) => multiplyNum * num
compose(increment, multiplyBy(3), increment)(4)// 4 > 5 > 15 > 16
答案 2 :(得分:2)
另一个简单的解决方案是分三步完成,只需像这样将 HOC 组件放在一起:
const firstHOC = withNotifications(TextComponent);
const secondHOC = withSocket(firstHOC);
export default withResource(secondHOC);