首页 > 解决方案 > 我应该在反应中使用带有 HOC 的柯里化吗?

问题描述

进行柯里化是性能较差还是不好的做法?是更好的表现还是更好的实践?或者这一切都只是偏好。我真的找不到关于这个问题的任何具体证据。

class MyClass extends React.component {
 ...
}
export default HOC(someParam)(MyClass)

对比:

class MyClass extends React.component {
 ...
}
export default HOC(someParam, MyClass)

示例 HOC(柯里化):

export default function HOC(someParam){
 // do something with someParam here
 return function(ChildComponent){
   return (props) => ( <ChildComponent {...props}/> )
 }
}

示例 HOC(不柯里化):

export default function HOC(someParam, childComponent){
 // do something with someParam here
 return (props) => ( <ChildComponent {...props}/> )
}

标签: javascriptreactjs

解决方案


在性能方面,任何差异都将微不足道,以至于无关紧要。创建函数需要几纳秒,而且你每堂课只需要做一次。

因此,决定应该归结为您是否从中获得好处。如果您使用大量高阶组件,您可能会发现使用组合将多个 HOC 组合在一起很有用。如果是这种情况,则柯里化将非常有用,因为组合通常要求函数是一元的。例如:

class MyClass extends React.Component {
  // whatever
}


export default compose(
  withI18n,
  withTheme,
  connect(state => ({ foo: state.foo }),
  HOC("someValue") // <-- this would be from your curried example
)(MyClass)

// Without composition, this would be the following... i think.
withI18n(withTheme(connect(state => ({ foo: state.foo }))(HOC("someValue", MyClass))));

推荐阅读