gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:02:12 24 4
gpt4 key购买 nike

我四处搜索并阅读了一些东西后,当我在 if-else 上使用 recompose branch 时仍然没有得到 react 中的陈述或为什么甚至使用它?谁能提到一个好的来源或解释一下?谢谢

最佳答案

它可以代替 if..else 或首选函数组合的三元运算符。 Recompose 提供 function composition对于 React 组件。作为其他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>
));

关于javascript - 为什么以及何时使用重组分支?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53800398/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com