只有在 props 中满足特定条件时才添加 HoC

Only add HoC if certain condition is met in the props

我正在使用重组库和 HoC 为我的组件传递一堆道具。我想知道在 compose 中是否有办法在设置 HoC 之前检查道具。例如,假设我有这样的东西:

export default compose(
  withProps(props => ({
    shouldUseWithMyHoc: someCondition() // true or false
  })),
  withState('someState', 'setSomeState', ''),
  withHandlers({
    doStuff: props => evt => {
      // do stuff
    }
  }),
  withMyHoc() // should only use if `shouldUseWithMyHoc` prop is true
)(MyComponent)

如何才能让 withMyHoc 仅在 shouldUseWithMyHoc 设置为 true 时使用?

我想过也许做一个三元组,但那并不顺利,当条件为假时我没有什么可以退缩的。它看起来像这样:

  export default compose (
  ...
  (props) => {(
    props.shouldUseWithMyHoc
    ? withMyHoc()
    : null)}
  )(MyComponent)

通过使用三元,我得到以下错误:

Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

有什么方法可以完成吗?如果这看起来是正确的,那么我做错了什么?

原来我只是需要在 google 上更好地表达我的问题。来自 recomposebranch HoC 解决了我的问题,正如指定的那样 here

对于我的组件,当我完成应用分支时,它是这样的:

export default compose(
  withProps(props => ({
    shouldUseWithMyHoc: someCondition() // true or false
  })),
  withState('someState', 'setSomeState', ''),
  withHandlers({
    doStuff: props => evt => {
      // do stuff
    }
  }),
  branch(
    (props) => props.shouldUseWithMyHoc,
    withMyHoc()
  )
)(MyComponent)