簡體   English   中英

為什么以及何時使用重組分支?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM