2017-05-03 52 views
1

我的组件之一有四种不同的状态,每种状态都有自己的全屏视图(加载,错误/重试和其他2种)。React Native:如何使用耦合条件呈现大量条件视图?

现在我的渲染功能如下:

render() { 
    return (
     <View style={{flex: 1, flexDirection: 'column'}}> 
      {this.renderLoadingView()} 
      {this.renderEmptyView()} 
      {this.renderErrorView()} 
      {this.renderInterviewListView()} 
      {this.renderInterviewFeedbackRequestViews()} 
     </View> 
    ); 
} 

但每个人的这个样子,他们要么使空,如果他们不符合若干条件或他们提供如果视图所有都满足:

renderLoadingView() { 
    if (this.state.showLoading && !this.state.showError) { 
     return (
      <View> 
       [...] 
      </View> 
     ); 
    } else { 
     return null; 
    } 
} 

renderErrorView() { 
    if (this.state.showError) { 
     return (
      <InterviewsErrorView onRetry={() => this.onRefresh()}/> 
     ); 
    } else { 
     return null; 
    } 
} 

renderInterviewListView() { 
    var showEmpty = this.state.emptyFeedbackRequests && this.state.emptyInterviews; 
    if (this.state.showLoading || this.state.showError || showEmpty) { 
     return null; 
    } else if (!this.state.emptyFeedbackRequests) { 
     return null; 
    } else { 
     return (
      <View> 
       [...] 
      </View> 
     ); 
    } 
} 

这种感觉凌乱,尤其是因为多个视图依赖于同样的事情(如是否showLoading是真的)。有没有一种方法可以简化或使其更清洁?

回答

2

在渲染方法中使用您的条件并将其从辅助方法中移除。您的渲染方法应该如下所示:

render() { 

    const showEmpty = this.state.emptyFeedbackRequests && this.state.emptyInterviews; 

    return (
    <View style={{flex: 1, flexDirection: 'column'}}> 
     { this.state.showLoading && this.state.showError && this.renderLoadingView()} 
     {this.renderEmptyView()} 
     {this.state.showError && this.renderErrorView()} 
     {(this.state.showLoading || this.state.showError || shosEmpty) && this.renderInterviewListView()} 
     {this.renderInterviewFeedbackRequestViews()} 
    </View> 
); 
} 

这将使您的帮助程序方法变得更加清晰,并会从其中移除其他部分。通过查看您的问题,我无法确定您的视图中的通用代码。

但是,如果有一些共同点,您可以通过在方法中引入参数来进一步优化代码并减少辅助方法的数量。