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

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

您可以使用compose终极版重构.例如:

终极版

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)

  • @Ehsansarshar也可以。这种方法的问题在于,很难推断出正在使用哪些HOC。特别是如果将来任何这些HOC更改其签名。进行更改将更加困难。想象一下,您有一个包含大量HOC的组件:`withHOC1(withHOC2(withHOC3(withHOC4(withHOC5(withHOC6)))))......我认为它不够可读。 (2认同)

Pur*_*lex 11

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

:由自己或使用来自就像一个图书馆写它lodashrambdaredux,等。

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)