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

Lin*_*son 5 javascript reactjs recompose

我四处搜索,阅读了一些东西后,当我在反应中使用recompose branchoverif-else语句时,我仍然没有得到,或者为什么要使用它?任何人都可以提到一个好的来源或解释它吗?谢谢

Est*_*ask 5

if..else在首选函数组合的情况下,它可以代替或 三元运算符使用。Recompose为 React 组件提供了函数组合。与其他Recompose 高阶组件一样branchHOC 可以由以下组件组成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);
Run Code Online (Sandbox Code Playgroud)

所涉及的所有功能SomeExampleComponent都是可重用的,可以单独测试和使用。

如果情况很简单并且这些函数不希望与任何组件一起使用,除了ExampleComponent,它可以简化为:

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