我的一个组件之一具有大约四个不同的状态,每个状态都有自己的全屏视图(加载,错误/重试和其他2个(。
现在我的渲染功能看起来像:
render() {
return (
<View style={{flex: 1, flexDirection: 'column'}}>
{this.renderLoadingView()}
{this.renderEmptyView()}
{this.renderErrorView()}
{this.renderInterviewListView()}
{this.renderInterviewFeedbackRequestViews()}
</View>
);
}
但是,每个其他人看起来都像这样,如果他们不符合多个条件,则它们要么使null变得无效,要么在满足所有情况时会呈现视图:
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是否为真(。有什么方法可以简化或使其更干净?
在渲染方法中使用您的条件,然后将其从辅助方法中删除。您的渲染方法应该看起来像:
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>
);
}
这将使您的助手方法清洁,并将从中删除其他部分。通过查看您的问题,我无法确定您的观点中的常见代码。
但是,如果有常见的东西,您可以通过在方法中引入参数进一步优化代码和减少辅助方法的数量。