首页 > 解决方案 > Mobx 加载包装器 React

问题描述

问题

建议的解决方案1:

// LoadingWrapperWithFailure.js

@observer
class LoadingWrapperWithFailure extends React.Component {
  render() {
    const { apiStatus, apiError, children, onRetry } = this.props;

    switch (apiStatus) {
      case API_FETCHING:
        // Loading state
        return <LoadingView loaderProps={loaderProps} />;
      case API_SUCCESS:
        // Success state
        return children;
      case API_FAILED:
        // Failed state
        return <FailureView onRetry={onRetry} apiError={apiError} />;
      default:
        return null;
    }
  }
}
// Usage

@observer
class ProductList extends React.Component {
  render() {
    const {
      apiStatus,
      apiError,
      productList,
      onRetryApi
    } = this.props.productStore;
    return (
      <LoadingWrapperWithFailure
        apiStatus={apiStatus}
        apiError={apiError}
        onRetry={onRetryApi}
      >
        <SuccessView>
          {/* Renders productList when apicall is success */}
        </SuccessView>
      </LoadingWrapperWithFailure>
    );
  }
}
> Note: apiStatus, apiError, productList are mobx observable variables

建议的解决方案 2:

// LoadingWrapperWithFailure.js

@observer
class LoadingWrapperWithFailure extends React.Component {
  render() {
    const { apiStatus, apiError, renderSuccessUI: RenderSuccessUI, onRetry } = this.props;

    switch (apiStatus) {
      case API_FETCHING:
        // Loading state
        return <LoadingView loaderProps={loaderProps} />;
      case API_SUCCESS:
        // Success state
        return <RenderSuccessUI />;
      case API_FAILED:
        // Failed state
        return <FailureView onRetry={onRetry} apiError={apiError} />;
      default:
        return null;
    }
  }
}
// Usage

@observer
class ProductList extends React.Component {

  renderSuccessUI = observer(() => {
    const { productList } = this.props.productStore
    return (
      <SuccessView>
          {/* Renders productList when apicall is success */}
      </SuccessView>
    )
  })

  render() {
    const {
      apiStatus,
      apiError,
      onRetryApi
    } = this.props.productStore;
    return (
      <LoadingWrapperWithFailure
        apiStatus={apiStatus}
        apiError={apiError}
        onRetry={onRetryApi}
        renderSuccessUI={this.renderSuccessUI}
      />
    );
  }
}

最好的方法是什么?

为什么这是最好的方法?

还有其他更好的方法来实现上述功能吗?

如果您需要更多信息,请发表评论。TIA。

标签: javascriptreactjsmobxreact-dommobx-react

解决方案


推荐阅读