[英]why and when use recompose branch?
我四处搜索并阅读了一些东西后,当我在反应中使用recompose
branch
而不是if-else
语句时我仍然没有得到,或者为什么还要使用它? 谁能提到一个好的来源或解释一下? 谢谢
在首选函数组合的情况下,它可以代替if..else
或三元运算符使用。 Recompose 为 React 组件提供功能组合。 与其他Recompose 高阶组件一样, 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>
));
从重组分支是避免组件中出现 if-else 的最佳方法之一
branch(
condition,
leftHOC,
rightHOC
)(MyComponent)
如果条件评估为真则
MyComponent传递给leftHOC ,否则传递给rightHOC
假设你必须在数据不可用之前显示加载状态,那么我们也可以使用recompose中的renderComponent
branch(
props=>props.loading,
renderComponent(Loader),
myComponent=>myComponent,
)(MyComponent)
虽然 Estus 的回答足够好,并且回答了如何使用而不是 if..else 或三元运算符,但我想提一下我们在项目中使用的分支的另一个用例,当我们想要在另一个组件中渲染一个组件时在 renderComponent() 的帮助下的一些条件与 branch() 结合使用(在我们的项目中通常我们用它来渲染哑组件,模态组件等)
branch<WrappedProps>(
props => props.success,
renderComponent(ShowSuccessModal)
)
所以在这个例子中,只要我们容器中的props.success
变为真,模态组件就会被渲染。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.