2017-10-12 101 views
0

我有一個名爲PartyDetails的組件,它需要通過ajax調用獲取數據。我想在ajax請求正在進行時顯示Loading組件。有沒有更好的方法來處理這個redux重構分支用例?

問題是,爲了確定數據是否加載,我需要訪問商店。這就是我的增強看起來像:

const enhance = compose(
    propSetter, 
    lifecycleEnhancer, 
    loading, 
) 

export default enhance(PartyDetails) 

其中propSetter是:

const propSetter = connect((state) => { 
    const { party } = state 
    const { dataLoaded } = party 
    // for some reason state does not contain match, and I'm resorting to routing 
    const { routing: {location: { pathname }}} = state 
    const involvedPartyId = pathname.substring(pathname.lastIndexOf('/') + 1) 
    return { dataLoaded, involvedPartyId } 
}, {loadParty}) 

lifecycleEnhancer是:

const lifecycleEnhancer = lifecycle({ 
    componentDidMount() { 
     this.props.loadParty(this.props.involvedPartyId) 
    } 
}) 

loading的(請注意,在這種情況下,dataLoaded來自已在propSetter中完成的前connect):

const loading = branch(
    ({dataLoaded}) => dataLoaded, 
    renderComponent(connect(mapStateToProps, mapDispatchToProps)(PartyDetails)), 
    renderComponent(Loading) 
) 

所以基本上,如果數據已經被提取,我使用第二個連接來獲取PartyDetails的相關道具。

我剛剛開始學習recompose幾天前,我找不到一個適合我的用例的例子。以上是我在閱讀完文檔後提出的,以及其他文章中的一些例子。

我正在做一個很好的處理方法?這是否可以以更好的方式完成,也許不需要撥打電話?

回答

0

你可以寫映射狀態和調度道具所有的邏輯在一個連接:

export default compose(
    connect(
    state => { 
     const { party } = state; 
     const { dataLoaded } = party; 
     const { routing: { location: { pathname } } } = state; 
     const involvedPartyId = pathname.substring(pathname.lastIndexOf("/") + 1); 

     // also put here your `mapStateToProps` code 

     return { dataLoaded, involvedPartyId }; 
    }, 
    { 
     loadParty 
     // the same here, append `mapDispatchToProps` logic 
    } 
), 
    lifecycle({ 
    componentDidMount() { 
     this.props.loadParty(this.props.involvedPartyId); 
    } 
    }), 
    branch(
    ({ dataLoaded }) => dataLoaded, 
    renderComponent(PartyDetails), 
    renderComponent(Loading) 
) 
    // as `branch` is returning HOC, we need to provide empty component to it in 
    // order to render whole component 
)(createSink()); 
+0

我沒有在一個連接一切的原因是,數據不會在狀態,當第一存在連接被調用。你的例子中有什麼我想念的嗎? – Geo

+0

@Geo它實際上不是問題。在我的例子中,首先渲染數據變量將是未定義的(因爲它當時不存在),我們將呈現'Loading'組件,其中不需要該數據。在第二次渲染時,當從服務器獲取數據時,我們將渲染「PartyDetails」並傳遞派生數據 – 1ven

相關問題