2017-09-04 35 views
1

我正在使用React Native應用程序。在應用程序中,當用戶登錄時,會向服務器發出API調用,以使用redux-saga來獲取數據。在redux存儲中,我維護一個布爾變量「fetchingData」。一旦API調用被啓動,它被設置爲'true'並且一旦數據被提取或發生一些錯誤,就被設置爲'false'。現在,我想在數據被提取時顯示一個微調,並在數據被提取時顯示一個FlatList。我知道我可以通過將return語句包裝進if-else條件來做到這一點。我想應該有一些更好的方法來做到這一點。 如果有人能幫助我,請告訴我一種在React Native中實現這種有條件呈現的好方法。先謝謝你。在React Native中使用條件呈現的最佳方法

回答

1

我不這麼認爲。當調用render()方法時,適當的組件需要是基於狀態返回的。

render() { 
    const isLoading = this.state.isLoading 
    return isLoading ? 
     <Spinner /> //return a spinner 
     : 
     <FlatList /> return a list with data 
} 
1

如果這是你到處使用有幾種方法來抽象圖案了一個模式:

  1. 創建一個通用<Loading />組件:

    class Loading extends React.Component { 
        static defaultProps = { 
        waitingElement: <Spinner />, 
        renderedElement: null 
        }; 
    
        render() { 
        return this.props.loading ? this.props.waitingElement : this.props.renderedElement; 
        } 
    } 
    
    // In some other component's `render`:   
    <Loading renderedElement={<component with=props />}, loading={this.state.isWaiting} /> 
    
  2. 使用higher-訂購組件來包裝您的組件:

    function withLoading(Component, spinner = <Spinner />) { 
        return class extends Component { 
        render() { 
         if (this.props.loading) return spinner; 
         return super.render(); 
        } 
        }; 
    } 
    
    // Some other file completely 
    export default withLoading(class MyComponent { 
        render() { 
        return "Happy path only!"; 
        } 
    }); 
    
相關問題