使用多个 HOC 包装器导出 React 组件?

Exporting React component with multiple HOC wrappers?

我有一个显示样式文本的 React 组件,我想让它加载网络资源、侦听 WebSocket 输入并显示通知。为了做到这一点,我为以下每一个编写了高阶组件包装函数:withResourcewithSocketwithNotifications.

导出组件时,这样正确吗?

class TextComponent extends React.Component {
  ...
}

export default withResource(withSocket(withNotifications(TextComponent)))

您可以使用 redux or recompose 中的 compose。例如:

Redux

import { compose } from 'redux'

export default compose(
  withResource,
  withSocket,
  withNotifications
)(TextComponent)

重组

import { compose } from 'recompose'

export default compose(
  withResource,
  withSocket,
  withNotifications
)(TextComponent)

它被称为函数组合并且它具有数学背景(导致yx变量命名和函数的反向执行)。它通过消除变量额外定义和深层函数包装,降低了调用书面函数的方式的复杂性。

自己编写或从库中使用,例如:lodashrambdaredux

const compose = (...rest) => x => rest.reduceRight((y, f) => f(y), x)

使用第一个class函数

const increment = (numb) => numb + 1
const multiplyBy = (multiplyNum) => (num) => multiplyNum * num

compose(increment, multiplyBy(3), increment)(4)// 4 > 5 > 15 > 16

使用高阶组件

compose(withRouter, withItems, withRefs)(Component) 

另一个简单的解决方案可以分三步完成,只需将 HOC 组件放在彼此之上,如下所示:

const firstHOC = withNotifications(TextComponent);
const secondHOC = withSocket(firstHOC);
export default withResource(secondHOC);