我到处搜索,在读了一些东西后,我仍然不明白在react中使用recompose branch而不是if-else语句,或者为什么要使用它?有人能提到一个好的来源或解释一下吗?谢谢
发布于 2018-12-16 16:26:18
它可以用来代替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>
));发布于 2020-09-09 13:21:37
recompose中的分支是在组件中避免if-else的最佳方法之一
branch(
condition,
leftHOC,
rightHOC
)(MyComponent)如果条件的计算结果为true,则
将
MyComponent传递给leftHOC,否则将其传递给rightHOC
假设您必须在数据不可用之前显示加载状态,那么我们也可以使用recompose中的renderComponent
branch(
props=>props.loading,
renderComponent(Loader),
myComponent=>myComponent,
)(MyComponent)发布于 2019-01-08 18:58:58
虽然Estus的回答已经足够好了,并且回答了如何使用分支而不是if..else或三元运算符,但我想要提到我们在项目中使用的分支用例,当我们想要在renderComponent()的帮助下根据某些条件在另一个组件中呈现一个组件时,它与分支()结合使用很有用(在我们的项目中,我们通常使用它来呈现哑巴组件、模态组件等)。
branch<WrappedProps>(
props => props.success,
renderComponent(ShowSuccessModal)
)因此,在本例中,每当容器中的props.success变为true时,都会呈现模态组件。
https://stackoverflow.com/questions/53800398
复制相似问题