React Native:如何呈现多个具有耦合条件的条件视图?

React Native: How to render a number of conditional views with coupled conditions?

我的一个组件可能有大约四种不同的状态,每种状态都有自己的全屏视图(加载、error/retry 和其他 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>
  );
}

这将使您的辅助方法更清晰,并且也会从中删除 else 部分。通过查看您的问题,我无法确定您的视图中的通用代码。

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