为什么以及何时使用重组分支?

时间:2018-12-16 07:50:57

标签: javascript reactjs recompose

我已经四处搜寻,并且在阅读了一些东西之后,当我在K语句中使用recompose branch而不是在反应中还是为什么使用它时仍然没有得到结果? 谁能提到一个好的来源或对其进行解释? 谢谢

3 个答案:

答案 0 :(得分:4)

它可以代替if..else或首选函数组合的三元运算符使用。 Recompose为React组件提供function composition。与其他Recompose higher-order components一样,branch 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>
));

答案 1 :(得分:0)

虽然Estus答案足够好,并且回答了如何使用它代替if..else或三元运算符,但我想在项目中使用一个分支的用例,当我们想在另一个组件中渲染组件时Component在某些条件下借助于renderComponent(),它可以与branch()结合使用(在我们的项目中,我们通常使用它来渲染哑巴组件,模态组件等)

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

因此,在此示例中,只要容器中的props.success变为true,就将呈现模式组件。

答案 2 :(得分:0)

重构 中的

分支 是避免组件中if-else的最佳方法之一

branch(
   condition,
   leftHOC,
   rightHOC
)(MyComponent)

如果条件为真,则

MyComponent 传递给 leftHOC ,否则传递给 rightHOC

假设您必须显示加载状态,直到时间数据不可用,然后我们还可以使用 重新构建中的 renderComponent

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