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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48569635/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 08:06:47  来源:igfitidea点击:

Exporting React component with multiple HOC wrappers?

javascriptreactjshigher-order-components

提问by superhawk610

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.

我有一个显示样式文本的 React 组件,我想让它加载网络资源、监听 WebSocket 输入并显示通知。为了做到这一点,我写的高阶组件封装对于这些功能:withResourcewithSocket,和withNotifications

When exporting the component, is this correct?

导出组件时,是否正确?

class TextComponent extends React.Component {
  ...
}

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

回答by mersocarlin

You can use composefrom reduxor recompose. For example:

您可以使用composefrom reduxrecompose。例如:

Redux

终极版

import { compose } from 'redux'

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

Recompose

重组

import { compose } from 'recompose'

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

回答by Purkhalo Alex

It's called functional compositionand it has mathematical background (that causes yand xvariables naming and reversed execution of functions). It decreases complexity of the way how you call written functionsby eliminating variables extra definition and deep level of function wrapage.

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

Write it by yourself or use from a library like: lodash, rambda, redux, etc.

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

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

Usage with first class functions:

使用一流的功能

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

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

Usage with higher order components:

高阶组件一起使用

compose(withRouter, withItems, withRefs)(Component)