【问题标题】:why and when use recompose branch?为什么以及何时使用重组分支?
【发布时间】:2019-05-16 22:40:38
【问题描述】:

我四处搜索并阅读了一些东西后,当我在反应中使用 recompose branch 而不是 if-else 语句时仍然没有得到,或者为什么还要使用它? 谁能提到一个好的来源或解释它? 谢谢

【问题讨论】:

    标签: javascript reactjs recompose


    【解决方案1】:

    它可以用来代替if..else 或首选函数组合的三元运算符。 Recompose 为 React 组件提供了function composition。与其他Recompose higher-order componentsbranch HOC 一样可以与compose 组成:

    const fooPredicate = ({ type }) => (type === 'foo');
    const FooHOC = Comp => props => <Comp ...props>Foo</Comp>;
    const BarHOC = Comp => props => <Comp ...props type="bar">Bar</Comp>;
    const FooOrBarHOC = branch(fooPredicate, FooHOC, BarHOC);
    const SomeHOC = compose(BazHOC, FooOrBarHOC);
    const SomeExampleComponent = SomeHOC(ExampleComponent);
    

    SomeExampleComponent 中涉及的所有函数都是可重用的,可以相互分开测试和使用。

    如果情况很简单,并且这些函数预计不会与除ExampleComponent 之外的任何组件一起使用,则可以简化为:

    const SomeExampleComponent = BazHOC(props => (
      props.type === 'foo'
      ? <ExampleComponent ...props>Foo</ExampleComponent>
      : <ExampleComponent ...props type="bar">Bar</ExampleComponent>
    ));
    

    【讨论】:

      【解决方案2】:

      虽然 Estus 的回答已经足够好,并且回答了如何使用而不是 if..else 或三元运算符,但当我们想要在另一个组件中渲染组件时,我想再提一下我们在项目中使用的分支的用例在 renderComponent() 的帮助下基于某些条件的组件,它与 branch() 结合使用非常有用(在我们的项目中,通常我们使用它来渲染哑组件、模态组件等)

      branch<WrappedProps>(
        props => props.success,
        renderComponent(ShowSuccessModal)
      )
      

      所以在这个例子中,只要我们容器中的props.success 为真,模态组件就会被渲染。

      【讨论】:

        【解决方案3】:
        recompose 中的

        branch 是避免组件中出现 if-else 的最佳方法之一 p>

        branch(
           condition,
           leftHOC,
           rightHOC
        )(MyComponent)
        

        如果条件为真,那么

        MyComponent 被传递给 leftHOC 否则它被传递给 rightHOC

        假设您必须显示加载状态,直到数据不可用,那么我们也可以使用 recompose 中的 renderComponent

        branch(
           props=>props.loading,
           renderComponent(Loader),
           myComponent=>myComponent,
        )(MyComponent)
        

        【讨论】:

          猜你喜欢
          • 2013-06-13
          • 2021-01-24
          • 2013-01-05
          • 2017-03-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多